package com.ctshk.rpc.scenic.service.impl;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.constant.ElasticSearchConstant;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.ApprovalStatus;
import com.ctshk.common.enums.GlobalConstants;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.*;
import com.ctshk.rpc.order.scenic.dto.ScenicOrderDetailDTO;
import com.ctshk.rpc.order.scenic.req.ScenicOrderDetailReq;
import com.ctshk.rpc.order.scenic.service.IScenicOrderService;
import com.ctshk.rpc.scenic.dto.*;
import com.ctshk.rpc.scenic.dto.app.ScenicProductEsDTO;
import com.ctshk.rpc.scenic.entity.*;
import com.ctshk.rpc.scenic.mapper.*;
import com.ctshk.rpc.scenic.req.*;
import com.ctshk.rpc.scenic.req.app.ScenicProductEsReq;
import com.ctshk.rpc.scenic.service.IScenicProductService;
import com.ctshk.rpc.scenic.service.IScenicReservationService;
import com.ctshk.rpc.scenic.service.app.IScenicTicketEsSearchService;
import com.ctshk.rpc.system.dto.QueryAgentByNameDTO;
import com.ctshk.rpc.system.dto.ScenicDTO;
import com.ctshk.rpc.system.dto.SysDepartmentDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.req.ScenicDetailReq;
import com.ctshk.rpc.system.service.*;
import com.github.houbb.heaven.util.util.CollectionUtil;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.ctshk.rpc.scenic.constants.Constants.ADJUST_TYPE_FIXED;
import static com.ctshk.rpc.scenic.constants.Constants.ADJUST_TYPE_PERCENT;

/**
 * <p>
 *
 * </p>
 *
 * @author xuhui
 * @since 2/2/2021
 */
@DubboService
@Slf4j
public class ScenicProductServiceImpl extends ServiceImpl<ScenicProductMapper, ScenicProduct> implements IScenicProductService {

    @Autowired
    ScenicProductMapper scenicProductMapper;

    @DubboReference
    ISceneService sceneService;
    @DubboReference
    ISysAgentService iSysAgentService;
    @DubboReference
    IScenicTicketEsSearchService iScenicTicketEsSearchService;

    @Autowired
    ScenicProductSaleStrategyMapper scenicProductSaleStrategyMapper;

    @Autowired
    ScenicProductSaleStrategyVaildDateMapper scenicProductSaleStrategyVaildDateMapper;

    @Autowired
    ScenicProductChannelOfflineSelfCustomMapper scenicProductChannelOfflineSelfCustomMapper;

    @Autowired
    ScenicProductChannelOfflineAgentCustomMapper scenicProductChannelOfflineAgentCustomMapper;

    @Autowired
    ScenicProductChannelOnlineSelfPlatformMapper scenicProductChannelOnlineSelfPlatformMapper;

    @Autowired
    ScenicProductChannelOnlineThirdPlatformMapper scenicProductChannelOnlineThirdPlatformMapper;

    @Autowired
    ScenicProductChannelOfflineMapper scenicProductChannelOfflineMapper;

    @Autowired
    ScenicProductCostStrategySpecStockMapper scenicProductCostStrategySpecStockMapper;

    @Autowired
    ScenicProductCostStrategyMapper scenicProductCostStrategyMapper;

    @Autowired
    ScenicProductCostStrategyVaildDateMapper scenicProductCostStrategyVaildDateMapper;

    @Autowired
    ScenicProductTicketMapper scenicProductTicketMapper;

    @Autowired
    ScenicProductCostStrategySpecAttrMapper scenicProductCostStrategySpecAttrMapper;

    @DubboReference
    private ISysUserService iSysUserService;

    @DubboReference
    private ISysPermissionService sysPermissionService;

    @DubboReference
    IScenicOrderService scenicOrderService;
    @DubboReference
    IScenicReservationService iScenicReservationService;
    @DubboReference
    private ISysDepartmentService sysDepartmentService;
    private static final String IS_LIMIT = "无限制";

    private static final String start_sale_time_end = "2099-12-01 00:00:00";

    // 扫描起始时间
    private static LocalDateTime lastModifiedTime;

    @Autowired
    RestHighLevelClient restHighLevelClient;


    @Override
    public PageResponse<ScenicProductListDTO> list(ScenicProductListReq req, TokenUser currentUser) {
        if (!GlobalConstants.Role.isAdmin(currentUser.getUsername())) {
            if (req.getMenuId() == null) {
                throw new BusinessException(SystemError.SYSTEM_2106);
            }
            Result<List<Long>> permissionResult = sysPermissionService.queryPermission(req.getMenuId(), currentUser.getId());
            if (!permissionResult.isSuccess()) {
                SystemError result = SystemError.getDefined(permissionResult.getCode());
                throw new BusinessException(result);
            }
            req.setChargeUserIds(permissionResult.getData());
            req.setUserId(currentUser.getId());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        log.info("开始查询 ---- " + sdf.format(new Date()));
        QueryWrapper<ScenicProduct> listWrapper = new QueryWrapper<>();
        listWrapper.lambda().eq(req.getCityId() != null, ScenicProduct::getCityId, req.getCityId());
        listWrapper.lambda().eq(req.getScenicId() != null, ScenicProduct::getScenicId, req.getScenicId());
        listWrapper.lambda().eq(req.getSupplierId() != null, ScenicProduct::getSupplierId, req.getSupplierId());
        listWrapper.lambda().eq(req.getSourceType() != null, ScenicProduct::getSourceType, req.getSourceType());
        listWrapper.lambda().eq(req.getStatus() != null, ScenicProduct::getStatus, req.getStatus());
        listWrapper.lambda().like(req.getName() != null, ScenicProduct::getName, req.getName());
        listWrapper.lambda().like(req.getProductCode() != null, ScenicProduct::getProductCode, req.getProductCode());
        //listWrapper.lambda().notIn(ScenicProduct::getAllowPackage, 3);
        if (req.getStatus() != null && req.getStatus().intValue() == 0) {
            listWrapper.lambda().eq(ScenicProduct::getStatus, req.getStatus());
            listWrapper.lambda().eq(ScenicProduct::getStatus, null);
        }
        listWrapper.lambda().eq(req.getIsRecommend() != null, ScenicProduct::getIsRecommend, req.getIsRecommend());
        listWrapper.lambda().orderByDesc(ScenicProduct::getGmtCreate);
        //售卖状态为有效
        listWrapper.eq("sale_status", 1);
        //审批通过
        listWrapper.eq("approval_status", ApprovalStatus.REVIEW_YES.getCode());
        //预订中心景点门票,查询上架的门票
        if ("2".equals(req.getType())) {
            listWrapper.lambda().eq(ScenicProduct::getStatus, 1);
        }

        if (req.getUserId() != null && CollectionUtils.isNotEmpty(req.getChargeUserIds())) {
            listWrapper.and(e -> e.eq("create_id", req.getUserId()).or().in("charge_user_id", req.getChargeUserIds()));
        } else {
            if (req.getUserId() != null) {
                listWrapper.eq("create_id", req.getUserId());
            }
            if (CollectionUtils.isNotEmpty(req.getChargeUserIds())) {
                listWrapper.in("charge_user_id", req.getChargeUserIds());
            }
        }
        Page<ScenicProduct> iPage = new Page<>(req.getPageNo(), req.getPageSize());
        log.info("准备执行查询SQL ---- " + sdf.format(new Date()));
        iPage = scenicProductMapper.selectPage(iPage, listWrapper);
        log.info("查询完成 ---- " + sdf.format(new Date()));
        if(iPage.getRecords().size() == 0){
            //查询结果未空
            return null;
        }
        Supplier<ScenicDetailReq> supplier = ScenicDetailReq::new;
        List<ScenicProductListDTO> scenicProductListDTOList = EntityUtil.copyList(iPage.getRecords(), ScenicProductListDTO.class);


        log.info("准备进行跨服服务调用 ---- " + sdf.format(new Date()));
        List<Long> scenicIds = iPage.getRecords().stream().map(ScenicProduct::getScenicId).collect(Collectors.toList());
        Result<List<ScenicDTO>> listResult = sceneService.quertByids(StringUtils.join(scenicIds, ","));
        Map<Long, ScenicDTO> scenicMap = new HashMap<>();
        for (ScenicDTO scenic : listResult.getData()) {
            scenicMap.put(scenic.getId(), scenic);
        }
        log.info("跨服务查询完成 ---- " + sdf.format(new Date()));
        Iterator<ScenicProductListDTO> it = scenicProductListDTOList.iterator();
        while (it.hasNext()) {
            ScenicProductListDTO dto = it.next();
            if ("2".equals(dto.getStartSaleTimeType())) {
                if (DateUtil.toLocalDate(dto.getStartSaleTimeBegin()).isAfter(DateUtil.toLocalDate(LocalDateTime.now()))
                        || DateUtil.toLocalDate(dto.getStartSaleTimeEnd()).isBefore(DateUtil.toLocalDate(LocalDateTime.now()))) {
                    it.remove();
                }
            }
        }
        scenicProductListDTOList = scenicProductListDTOList.stream().map(dto -> {
            ScenicDTO scenic = scenicMap.get(dto.getScenicId());
            if (!Objects.isNull(scenic)) {
                dto.setScenicName(scenic.getName());
                dto.setScenicLocation(scenic.getScenicLocation());
                dto.setScenicLevel(scenic.getScenicLevel());
                dto.setPhotosJson(null);
                dto.setCustomerNotice(null);
                dto.setProductIntroduces(null);
            }
            return dto;
        }).collect(Collectors.toList());

        log.info("匹配完成 ---- " + sdf.format(new Date()));

        PageResponse<ScenicProductListDTO> result = new PageResponse<>(scenicProductListDTOList, iPage.getCurrent() == 1,
                iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());

        log.info("接口计算完成 ---- " + sdf.format(new Date()));

        log.info("长度为：" + result.toString().getBytes().length);
        return result;
    }

    @Override
    public Result modifyRecommendStatus(ScenicProductModifyRecommendStatusReq scenicProductModifyRecommendStatus, TokenUser currentUser) {
        ScenicProduct scenic = scenicProductMapper.selectById(scenicProductModifyRecommendStatus.getId());
        if (scenic != null) {
            scenic.setIsRecommend(scenicProductModifyRecommendStatus.getIsRecommend());
            scenicProductMapper.updateById(scenic);
        } else {
            throw new BusinessException(SystemError.MAINDATA_4021);
        }
        //刷新缓存
            CompletableFuture.runAsync(() -> {
                List<Long> ids = new ArrayList<>();
                ids.add(Long.parseLong(scenicProductModifyRecommendStatus.getId()));
                List<ScenicProductEsDTO> reqList = scenicProductMapper.selectAllProductListByids(ids);
                ScenicProductEsReq req1 = new ScenicProductEsReq();
                for(ScenicProductEsDTO dto : reqList) {
                    BeanUtils.copyProperties(dto,req1);
                    iScenicTicketEsSearchService.cacheUpdate(req1);
                }

            });

        return Result.success(scenic.getId());

    }

    @Override
    public Integer queryUsageModeById(Long id) {
        return scenicProductMapper.queryUsageModeById(id);
    }

    @Transactional
    @Override
    public Result putAway(ScenicProductBatchSaleStrategyReq req, TokenUser currentUser) {
        Long userId = currentUser == null ? null : currentUser.getId();
        if (req.getScenicProductIdList() != null && req.getScenicProductIdList().size() >= 1) {
            Set<LocalDate> localDateSet = Sets.newHashSet();
            int localDateSize = 0;
            List<ScenicProductSaleStrategyReq> airProductSaleStrategyReqList = req.getStrategyList();
            if (CollectionUtil.isEmpty(airProductSaleStrategyReqList)) {
                return Result.failed(SystemError.AIR_PRODUCT_12007);
            }
            for (ScenicProductSaleStrategyReq strategyReq : airProductSaleStrategyReqList) {
                List<ScenicTimeDTO> reqTime = strategyReq.getTime();
                if (CollectionUtil.isEmpty(reqTime)) {
                    throw new BusinessException(SystemError.AIR_PRODUCT_12008);
                }
                for (ScenicTimeDTO timeDTO : reqTime) {
                    LocalDate dateBegin = timeDTO.getBeginTime();
                    LocalDate dateEnd = timeDTO.getEndTime();
                    List<LocalDate> dates = Stream.iterate(dateBegin, date -> date.plusDays(1))
                            .limit(ChronoUnit.DAYS.between(dateBegin, dateEnd))
                            .collect(Collectors.toList());
                    dates.add(dateEnd);
                    localDateSet.addAll(dates);
                    localDateSize += dates.size();
                }
            }
            if (localDateSet.size() != localDateSize) {
                return Result.failed(SystemError.BUS_PRODUCT_9022);
            }
            for (Long productId : req.getScenicProductIdList()) {
                ScenicProduct scenicProduct = scenicProductMapper.selectById(productId);
                scenicProduct.setStatus(1);
                scenicProduct.setModifiedId(currentUser.getId());
                scenicProduct.setGmtModified(LocalDateTime.now());
                scenicProductMapper.updateById(scenicProduct);
                List<ScenicProductSaleStrategyReq> strategyList = req.getStrategyList();
                if (strategyList != null && strategyList.size() >= 1) {
                    //校验日期是否有冲突
                    Result result = checkCostateResult(req.getStrategyList());
                    if (!Objects.isNull(result)) {
                        return result;
                    }
                    QueryWrapper<ScenicProductSaleStrategy> scenicProductSaleStrategyQueryWrapper = new QueryWrapper<>();
                    scenicProductSaleStrategyQueryWrapper.eq("product_id", productId);
                    scenicProductSaleStrategyQueryWrapper.eq("is_deleted", 0);
                    List<ScenicProductSaleStrategy> scenicProductSaleStrategies = scenicProductSaleStrategyMapper.selectList(scenicProductSaleStrategyQueryWrapper);
                    if (CollectionUtils.isNotEmpty(scenicProductSaleStrategies)) {
                        scenicProductSaleStrategyMapper.clearByProductId(productId, currentUser.getId());
                    }
                    scenicProductSaleStrategyVaildDateMapper.clearByProductId(productId, userId);
                    scenicProductChannelOfflineAgentCustomMapper.clearByProductId(productId, userId);
                    scenicProductChannelOfflineSelfCustomMapper.clearByProductId(productId);
                    scenicProductChannelOnlineSelfPlatformMapper.clearByProductId(productId, userId);
                    scenicProductChannelOnlineThirdPlatformMapper.clearByProductId(productId, userId);
                    scenicProductChannelOfflineMapper.clearByProductId(productId, userId);
                    //先清空该产品下的所有策略 然后再插入
                    for (ScenicProductSaleStrategyReq scenicProductSaleStrategyReq : strategyList) {
                        //新增
                        //新增门票销售加幅策略
                        Long id = SnowflakeIdWorker.nextId();
                        ScenicProductSaleStrategy scenicProductSaleStrategy = new ScenicProductSaleStrategy();
                        scenicProductSaleStrategy.setId(id);
                        scenicProductSaleStrategy.setCreateId(userId);
                        scenicProductSaleStrategy.setIsDeleted(0);
                        scenicProductSaleStrategy.setGmtCreate(LocalDateTime.now());
                        scenicProductSaleStrategy.setProductId(productId);
                        scenicProductSaleStrategy.setName(scenicProductSaleStrategyReq.getName());
                        scenicProductSaleStrategyMapper.insert(scenicProductSaleStrategy);
                        //新增门票销售价格加幅有效期
                        List<ScenicTimeDTO> time = scenicProductSaleStrategyReq.getTime();
                        if (time != null && time.size() >= 1) {
                            List<ScenicProductSaleStrategyVaildDate> list = new ArrayList<>();
                            for (ScenicTimeDTO scenicTimeDTO : time) {
                                ScenicProductSaleStrategyVaildDate scenicProductSaleStrategyVaildDate = new ScenicProductSaleStrategyVaildDate();
                                scenicProductSaleStrategyVaildDate.setProductId(productId);
                                scenicProductSaleStrategyVaildDate.setGmtCreate(LocalDateTime.now());
                                scenicProductSaleStrategyVaildDate.setTimeBegin(scenicTimeDTO.getBeginTime());
                                scenicProductSaleStrategyVaildDate.setTimeEnd(scenicTimeDTO.getEndTime());
                                scenicProductSaleStrategyVaildDate.setStrategyId(id);
                                list.add(scenicProductSaleStrategyVaildDate);
                            }
                            //插入
                            scenicProductSaleStrategyVaildDateMapper.insertBatchSomeColumn(list);
                        }
                        ChannelSaleReq channelSaleReq = scenicProductSaleStrategyReq.getChannelSaleReq();
                        //新增线下渠道
                        ScenicProductOfflineChannelReq scenicProductOfflineChannelReq = channelSaleReq.getScenicProductOfflineChannelReq();
                        if (scenicProductOfflineChannelReq != null) {
                            Long officeId = SnowflakeIdWorker.nextId();
                            ScenicProductChannelOfflineSelfCustom scenicProductChannelOfflineSelfCustom = new ScenicProductChannelOfflineSelfCustom();
                            scenicProductChannelOfflineSelfCustom.setProductId(productId);
                            scenicProductChannelOfflineSelfCustom.setGmtCreate(LocalDateTime.now());
                            scenicProductChannelOfflineSelfCustom.setCreateId(userId);
                            scenicProductChannelOfflineSelfCustom.setOfflineId(officeId);
                            scenicProductChannelOfflineSelfCustom.setIsDeleted(0);
                            ScenicProductChannelOffline scenicProductChannelOffline = new ScenicProductChannelOffline();
                            scenicProductChannelOffline.setProductId(productId);
                            scenicProductChannelOffline.setChannelType(1);
                            scenicProductChannelOffline.setCreateId(userId);
                            scenicProductChannelOffline.setGmtCreate(LocalDateTime.now());
                            scenicProductChannelOffline.setIsDeleted(0);
                            scenicProductChannelOffline.setStrategyId(id);
                            scenicProductChannelOffline.setId(officeId);

                            switch (scenicProductOfflineChannelReq.getVisableType()) {
                                case 1:
                                    scenicProductChannelOffline.setVisableType(1);
                                    scenicProductChannelOfflineMapper.insert(scenicProductChannelOffline);
                                    break;
                                case 2:
                                    scenicProductChannelOffline.setVisableType(2);
                                    scenicProductChannelOfflineMapper.insert(scenicProductChannelOffline);
                                    if (scenicProductOfflineChannelReq.getAdjustType() != null && scenicProductOfflineChannelReq.getAdjustType() == ADJUST_TYPE_FIXED) {
                                        scenicProductChannelOfflineSelfCustom.setAdjustType(ADJUST_TYPE_FIXED);
                                        scenicProductChannelOfflineSelfCustom.setAmount(scenicProductOfflineChannelReq.getAmount());
                                    } else if (scenicProductOfflineChannelReq.getAdjustType() != null && scenicProductOfflineChannelReq.getAdjustType() == ADJUST_TYPE_PERCENT) {
                                        scenicProductChannelOfflineSelfCustom.setAdjustType(ADJUST_TYPE_PERCENT);
                                        scenicProductChannelOfflineSelfCustom.setPercent(scenicProductOfflineChannelReq.getPercent());
                                    }
                                    if (scenicProductOfflineChannelReq.getIsLimit() != null) {
                                        scenicProductChannelOfflineSelfCustom.setIsLimit(scenicProductOfflineChannelReq.getIsLimit());
                                        scenicProductChannelOfflineSelfCustom.setLimitNum(scenicProductOfflineChannelReq.getLimitNum());
                                    } else {
                                        scenicProductChannelOfflineSelfCustom.setIsLimit(0);
                                    }
                                    scenicProductChannelOfflineSelfCustomMapper.insert(scenicProductChannelOfflineSelfCustom);
                                    break;
                                case 3:
                                    scenicProductChannelOffline.setVisableType(3);
                                    scenicProductChannelOfflineMapper.insert(scenicProductChannelOffline);
                                    List<ScenicProductChannelOfflineSelfCustomReq> scenicProductChannelOfflineSelfCustomReqList = scenicProductOfflineChannelReq.getScenicProductChannelOfflineSelfCustomReqList();
                                    if (scenicProductChannelOfflineSelfCustomReqList != null) {
                                        for (ScenicProductChannelOfflineSelfCustomReq customReq : scenicProductChannelOfflineSelfCustomReqList) {
                                            scenicProductChannelOfflineSelfCustom.setCheckType(customReq.getCheckType());
                                            scenicProductChannelOfflineSelfCustom.setName(customReq.getName());
                                            scenicProductChannelOfflineSelfCustom.setRelationId(customReq.getRelationId());
                                            if (customReq.getAdjustType() == ADJUST_TYPE_FIXED && customReq.getAdjustType() != null) {
                                                scenicProductChannelOfflineSelfCustom.setAdjustType(ADJUST_TYPE_FIXED);
                                                scenicProductChannelOfflineSelfCustom.setAmount(scenicProductOfflineChannelReq.getAmount());
                                            } else if (customReq.getAdjustType() == ADJUST_TYPE_PERCENT && customReq.getAdjustType() != null) {
                                                scenicProductChannelOfflineSelfCustom.setAdjustType(ADJUST_TYPE_PERCENT);
                                                scenicProductChannelOfflineSelfCustom.setPercent(scenicProductOfflineChannelReq.getPercent());
                                            }

                                            if (customReq.getIsLimit() != null) {
                                                scenicProductChannelOfflineSelfCustom.setIsLimit(customReq.getIsLimit());
                                                scenicProductChannelOfflineSelfCustom.setLimitNum(scenicProductOfflineChannelReq.getLimitNum());
                                            } else {
                                                scenicProductChannelOfflineSelfCustom.setIsLimit(0);
                                            }

                                            scenicProductChannelOfflineSelfCustom.setId(SnowflakeIdWorker.nextId());
                                            scenicProductChannelOfflineSelfCustomMapper.insert(scenicProductChannelOfflineSelfCustom);
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }

                        }
                        //新增代理商
                        ScenicProductAgentReq scenicProductAgentReq = channelSaleReq.getScenicProductAgentReq();
                        if (scenicProductAgentReq != null) {
                            Long offLineId = SnowflakeIdWorker.nextId();
                            ScenicProductChannelOffline scenicProductChannelOffline = new ScenicProductChannelOffline();
                            scenicProductChannelOffline.setProductId(productId);
                            scenicProductChannelOffline.setChannelType(2);
                            scenicProductChannelOffline.setCreateId(userId);
                            scenicProductChannelOffline.setIsDeleted(0);
                            scenicProductChannelOffline.setStrategyId(id);
                            scenicProductChannelOffline.setId(offLineId);
                            //代理商
                            ScenicProductChannelOfflineAgentCustom scenicProductChannelOfflineAgentCustom = new ScenicProductChannelOfflineAgentCustom();
                            scenicProductChannelOfflineAgentCustom.setProductId(productId);
                            scenicProductChannelOfflineAgentCustom.setGmtCreate(LocalDateTime.now());
                            scenicProductChannelOfflineAgentCustom.setCreateId(userId);
                            scenicProductChannelOfflineAgentCustom.setOfflineId(offLineId);
                            scenicProductChannelOfflineAgentCustom.setId(SnowflakeIdWorker.nextId());

                            switch (scenicProductAgentReq.getVisableType()) {
                                case 1:
                                    scenicProductChannelOffline.setVisableType(1);
                                    scenicProductChannelOfflineMapper.insert(scenicProductChannelOffline);
                                    break;
                                case 2:
                                    scenicProductChannelOffline.setVisableType(2);
                                    scenicProductChannelOfflineMapper.insert(scenicProductChannelOffline);
                                    if (scenicProductAgentReq.getAdjustType() != null && scenicProductAgentReq.getAdjustType() == ADJUST_TYPE_FIXED) {
                                        scenicProductChannelOfflineAgentCustom.setAmount(scenicProductAgentReq.getAmount());
                                        scenicProductChannelOfflineAgentCustom.setAdjustType(ADJUST_TYPE_FIXED);
                                    } else if (scenicProductAgentReq.getAdjustType() != null && scenicProductAgentReq.getAdjustType() == ADJUST_TYPE_PERCENT) {
                                        scenicProductChannelOfflineAgentCustom.setAdjustType(ADJUST_TYPE_PERCENT);
                                        scenicProductChannelOfflineAgentCustom.setPercent(scenicProductAgentReq.getPercent());
                                    }
                                    if (scenicProductAgentReq.getIsLimit() != null) {
                                        scenicProductChannelOfflineAgentCustom.setIsLimit(scenicProductAgentReq.getLimitNum());
                                        scenicProductChannelOfflineAgentCustom.setLimitNum(scenicProductAgentReq.getLimitNum());
                                    } else {
                                        scenicProductChannelOfflineAgentCustom.setLimitNum(scenicProductAgentReq.getLimitNum());
                                    }
                                    scenicProductChannelOfflineAgentCustomMapper.insert(scenicProductChannelOfflineAgentCustom);
                                    break;
                                case 3:
                                    scenicProductChannelOffline.setVisableType(3);
                                    scenicProductChannelOfflineMapper.insert(scenicProductChannelOffline);
                                    List<ScenicProductChannelOfflineAgentCustomReq> scenicProductChannelOfflineAgentCustomReqList = scenicProductAgentReq.getScenicProductChannelOfflineAgentCustomReqList();
                                    if (scenicProductChannelOfflineAgentCustomReqList != null) {
                                        for (ScenicProductChannelOfflineAgentCustomReq req1 : scenicProductChannelOfflineAgentCustomReqList) {
                                            scenicProductChannelOfflineAgentCustom.setId(SnowflakeIdWorker.nextId());
                                            scenicProductChannelOfflineAgentCustom.setAgentId(req1.getAgentId());
                                            scenicProductChannelOfflineAgentCustom.setAgentName(req1.getAgentName());
                                            if (req1.getAdjustType() != null && req1.getAdjustType() == ADJUST_TYPE_FIXED) {
                                                scenicProductChannelOfflineAgentCustom.setAdjustType(ADJUST_TYPE_FIXED);
                                                scenicProductChannelOfflineAgentCustom.setAmount(req1.getAmount());
                                            } else if (req1.getAdjustType() != null && req1.getAdjustType() == ADJUST_TYPE_PERCENT) {
                                                scenicProductChannelOfflineAgentCustom.setAdjustType(ADJUST_TYPE_PERCENT);
                                                scenicProductChannelOfflineAgentCustom.setPercent(req1.getPercent());
                                            }
                                            if (req1.getIsLimit() != null) {
                                                scenicProductChannelOfflineAgentCustom.setIsLimit(req1.getLimitNum());
                                                scenicProductChannelOfflineAgentCustom.setLimitNum(req1.getLimitNum());
                                            } else {
                                                scenicProductChannelOfflineAgentCustom.setIsLimit(0);
                                            }
                                            scenicProductChannelOfflineAgentCustomMapper.insert(scenicProductChannelOfflineAgentCustom);
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        //新增线下渠道官方平台
                        List<ScenicProductChannelOnlineSelfPlatformReq> scenicProductChannelOnlineSelfPlatformReqList = channelSaleReq.getScenicProductChannelOnlineSelfPlatformReqList();
                        if (scenicProductChannelOnlineSelfPlatformReqList != null) {
                            for (ScenicProductChannelOnlineSelfPlatformReq req1 : scenicProductChannelOnlineSelfPlatformReqList) {
                                ScenicProductChannelOnlineSelfPlatform scenicProductChannelOnlineSelfPlatform = new ScenicProductChannelOnlineSelfPlatform();
                                scenicProductChannelOnlineSelfPlatform.setId(SnowflakeIdWorker.nextId());
                                scenicProductChannelOnlineSelfPlatform.setStrategyId(id);
                                scenicProductChannelOnlineSelfPlatform.setProductId(productId);
                                scenicProductChannelOnlineSelfPlatform.setCreateId(userId);
                                scenicProductChannelOnlineSelfPlatform.setIsDeleted(0);
                                scenicProductChannelOnlineSelfPlatform.setGmtCreate(LocalDateTime.now());
                                scenicProductChannelOnlineSelfPlatform.setChannelId(req1.getChannelId());
                                scenicProductChannelOnlineSelfPlatform.setChannelName(req1.getChannelName());
                                if (req1.getAdjustType() != null && req1.getAdjustType() == ADJUST_TYPE_FIXED) {
                                    scenicProductChannelOnlineSelfPlatform.setAdjustType(ADJUST_TYPE_FIXED);
                                    scenicProductChannelOnlineSelfPlatform.setAmount(req1.getAmount());
                                } else if (req1.getAdjustType() != null && req1.getAdjustType() == ADJUST_TYPE_PERCENT) {
                                    scenicProductChannelOnlineSelfPlatform.setAdjustType(ADJUST_TYPE_PERCENT);
                                    scenicProductChannelOnlineSelfPlatform.setPercent(req1.getPercent());
                                }
                                if (req1.getIsLimit() != null) {
                                    scenicProductChannelOnlineSelfPlatform.setIsLimit(req1.getLimitNum());
                                    scenicProductChannelOnlineSelfPlatform.setLimitNum(req1.getLimitNum());
                                } else {
                                    scenicProductChannelOnlineSelfPlatform.setIsLimit(0);
                                }
                                scenicProductChannelOnlineSelfPlatformMapper.insert(scenicProductChannelOnlineSelfPlatform);
                            }
                        }
                        //新增线下渠道第三方平台
                        List<ScenicProductChannelOnlineThirdPlatformReq> scenicProductChannelOnlineThirdPlatformReqList = channelSaleReq.getScenicProductChannelOnlineThirdPlatformReqList();
                        if (scenicProductChannelOnlineThirdPlatformReqList != null) {
                            for (ScenicProductChannelOnlineThirdPlatformReq req1 : scenicProductChannelOnlineThirdPlatformReqList) {
                                ScenicProductChannelOnlineThirdPlatform scenicProductChannelOnlineThirdPlatform = new ScenicProductChannelOnlineThirdPlatform();
                                scenicProductChannelOnlineThirdPlatform.setProductId(productId);
                                scenicProductChannelOnlineThirdPlatform.setId(SnowflakeIdWorker.nextId());
                                scenicProductChannelOnlineThirdPlatform.setIsDeleted(0);
                                scenicProductChannelOnlineThirdPlatform.setCreateId(userId);
                                scenicProductChannelOnlineThirdPlatform.setPlatformId(req1.getPlatformId());
                                scenicProductChannelOnlineThirdPlatform.setPlatformName(req1.getPlatformName());
                                scenicProductChannelOnlineThirdPlatform.setGmtCreate(LocalDateTime.now());
                                if (req1.getAdjustType() != null && req1.getAdjustType() == ADJUST_TYPE_FIXED) {
                                    scenicProductChannelOnlineThirdPlatform.setAdjustType(ADJUST_TYPE_FIXED);
                                    scenicProductChannelOnlineThirdPlatform.setAmount(req1.getAmount());
                                } else if (req1.getAdjustType() != null && req1.getAdjustType() == ADJUST_TYPE_PERCENT) {
                                    scenicProductChannelOnlineThirdPlatform.setAdjustType(ADJUST_TYPE_PERCENT);
                                    scenicProductChannelOnlineThirdPlatform.setPercent(req1.getPercent());
                                }
                                if (req1.getIsLimit() != null) {
                                    if (req1.getIsLimit() == 0) {
                                        scenicProductChannelOnlineThirdPlatform.setIsLimit(0);
                                    } else {
                                        scenicProductChannelOnlineThirdPlatform.setIsLimit(1);
                                        scenicProductChannelOnlineThirdPlatform.setLimitNum(req1.getLimitNum());
                                    }
                                }
                                scenicProductChannelOnlineThirdPlatform.setStrategyId(id);
                                scenicProductChannelOnlineThirdPlatformMapper.insert(scenicProductChannelOnlineThirdPlatform);
                            }
                        }
                    }
                }

            }
        }
        //刷新ES缓存
            CompletableFuture.runAsync(() -> {
                List<ScenicProductEsDTO> reqList = scenicProductMapper.selectAllProductListByids(req.getScenicProductIdList());
                ScenicProductEsReq req1 = new ScenicProductEsReq();
                for(ScenicProductEsDTO dto : reqList) {
                    BeanUtils.copyProperties(dto,req1);
                iScenicTicketEsSearchService.cacheUpdate(req1);
                //更新redis缓存
                iScenicTicketEsSearchService.redisUpdate(req1);
                }
            });

        return Result.success();
    }

    @Override
    public Result<ScenicStockDetailDTO> stockDetail(ScenicProductStockDetailReq req, TokenUser currentUser) {
        QueryWrapper<ScenicProductCostStrategySpecStock> wrapper = new QueryWrapper<>();
        Optional o = Optional.ofNullable(req.getStrategyId());
        o.map(i -> wrapper.lambda().eq(ScenicProductCostStrategySpecStock::getStrategyId, i));
        o = Optional.ofNullable(req.getProductId());
        o.map(i -> wrapper.lambda().eq(ScenicProductCostStrategySpecStock::getProductId, i));
        ScenicProductCostStrategySpecStock s = scenicProductCostStrategySpecStockMapper.selectOne(wrapper);
        ScenicStockDetailDTO dto = EntityUtil.copy(s, ScenicStockDetailDTO.class);
        return Result.success(dto);
    }

    @Override
    public Result<ScenicProductDetailDTO> scenicProductDetai(ScenicProductReq scenicProductReq) throws ParseException {
        //這裏轉類型是因爲入参已經固定
        DecimalFormat df = new DecimalFormat("00");
        String date = String.format("%s-%s-01", scenicProductReq.getYear(), df.format(Integer.parseInt(scenicProductReq.getMonth())));
        LocalDate startDate =
                LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endDate = startDate.plusMonths(1);
        ScenicProductDetailDTO scenicProductDetailDTO = new ScenicProductDetailDTO();
        //查询产品详情
        ScenicProduct scenicProduct = scenicProductMapper.selectById(scenicProductReq.getProductId());
        if (scenicProduct != null) {
            ScenicProductListDTO scenicProductListDTO = EntityUtil.copy(scenicProduct, ScenicProductListDTO.class);
            ScenicDetailReq scenicDetailReq = new ScenicDetailReq();
            scenicDetailReq.setId(scenicProductListDTO.getScenicId());
            Result<ScenicDTO> result = sceneService.detail(scenicDetailReq);
            if (result.isSuccess()) {
                ScenicDTO scenicDTO = result.getData();
                if (scenicDTO != null) {
                    scenicProductListDTO.setScenicName(scenicDTO.getName());
                }
            }
            if ((scenicProduct.getReserveChargeType() != null) && scenicProduct.getReserveChargeType() == 1) {
                //类型是加数值
                scenicProductListDTO.setReserveCharge(scenicProduct.getReserveCharge().toString() + "HKD");
            } else if ((scenicProduct.getReserveChargeType() != null) && scenicProduct.getReserveChargeType() == 2) {
                //类型是百分比
                scenicProductListDTO.setReserveCharge(scenicProduct.getReserveCharge().toString() + "%");
            }
            if ((scenicProduct.getCtsChargeType() != null) && scenicProduct.getCtsChargeType() == 1) {
                //类型是加数值
                scenicProductListDTO.setCtsCharge(scenicProduct.getCtsCharge().toString() + "HKD");
            } else if ((scenicProduct.getCtsChargeType() != null) && scenicProduct.getCtsChargeType() == 2) {
                //类型是百分比
                scenicProductListDTO.setCtsCharge(scenicProduct.getCtsCharge().toString() + "%");
            }
            scenicProductListDTO.setNeedDoubleCheck(scenicProductListDTO.getBookConfirm());//是否需要二次確認
            scenicProductDetailDTO.setScenicProductListDTO(scenicProductListDTO);
        }
        QueryWrapper<ScenicProductSaleStrategy> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", scenicProductReq.getProductId());
        wrapper.eq("is_deleted", 0);
        //查一个产品下的所有策略
        List<ScenicProductSaleStrategy> list = scenicProductSaleStrategyMapper.selectList(wrapper);
        List<VaildDateDTO> dateDTOList = new ArrayList<>();
        for (ScenicProductSaleStrategy strategy : list) {
            List<OfflineCanalListDTO> offlineCanalListDTOList = new ArrayList<>();
            List<OnlineSelfListDTO> onlineSelfListDTOList = new ArrayList<>();
            //查询线下
            QueryWrapper<ScenicProductChannelOffline> offlineQueryWrapper = new QueryWrapper<>();
            offlineQueryWrapper.eq("is_deleted", 0);
            offlineQueryWrapper.eq("strategy_id", strategy.getId());
            // offlineQueryWrapper.eq("visable_type",3);
            List<ScenicProductChannelOffline> offlineList = scenicProductChannelOfflineMapper.selectList(offlineQueryWrapper);
            //綫下
            for (ScenicProductChannelOffline offline : offlineList) {
                switch (offline.getChannelType()) {
                    case 1:
                        QueryWrapper<ScenicProductChannelOfflineSelfCustom> selfCustomquery = new QueryWrapper<>();
                        selfCustomquery.eq("product_id", scenicProductReq.getProductId());
                        selfCustomquery.eq("offline_id", offline.getId());
                        selfCustomquery.eq("is_deleted", IsDeletedCode.NO.getCode());
                        List<ScenicProductChannelOfflineSelfCustom> selfCustoms = scenicProductChannelOfflineSelfCustomMapper.selectList(selfCustomquery);
                        //自營
                        switch (offline.getVisableType()) {
                            case 2:
                                OfflineCanalListDTO zyof2 = new OfflineCanalListDTO();
                                zyof2.setCanal("线下自营渠道-所有");
                                ScenicProductChannelOfflineSelfCustom selfCustom2 = selfCustoms.get(0);
                                if (Objects.isNull(selfCustom2.getIsLimit()) || selfCustom2.getIsLimit() == 0) {
                                    zyof2.setLimitNum("無限制");
                                } else {
                                    zyof2.setLimitNum(selfCustom2.getLimitNum().toString());
                                }
                                if (Objects.isNull(selfCustom2.getAdjustType()) ||
                                        selfCustom2.getAdjustType() == ADJUST_TYPE_FIXED) {
                                    BigDecimal amount = selfCustom2.getAmount() == null ? BigDecimal.ZERO : selfCustom2.getAmount();
                                    zyof2.setAddSize(amount.toString() + " " + "HKD");
                                } else if (selfCustom2.getAdjustType() == ADJUST_TYPE_PERCENT && selfCustom2.getPercent() != null) {
                                    //加幅类型是百分比
                                    zyof2.setAddSize(selfCustom2.getPercent().toString() + "%");
                                }
                                offlineCanalListDTOList.add(zyof2);
                                break;
                            case 3:
                                for (ScenicProductChannelOfflineSelfCustom off : selfCustoms) {
                                    OfflineCanalListDTO zyof3 = new OfflineCanalListDTO();
                                    if (off.getCheckType() == 1) {
                                        try {
                                            UserDTO userDTO = iSysUserService.loadUserByParam(off.getRelationId(), 1);
                                            zyof3.setCanal("线下自营渠道-" + userDTO.getUsername());
                                        } catch (Exception e) {
                                            new BusinessException(SystemError.SCENIC_5014);
                                        }
                                    } else if (off.getCheckType() == 2) {
                                        try {
                                            SysDepartmentDTO dto = sysDepartmentService.queryOne(off.getRelationId());
                                            zyof3.setCanal("线下自营渠道-" + dto.getTitle());
                                        } catch (Exception e) {
                                            new BusinessException(SystemError.SCENIC_5015);
                                        }
                                    }
                                    if (!Objects.isNull(off.getIsLimit()) || off.getIsLimit() == 0) {
                                        zyof3.setLimitNum("无限制");
                                    } else {
                                        zyof3.setLimitNum(off.getLimitNum().toString());
                                    }
                                    if (Objects.isNull(off.getAdjustType()) ||
                                            off.getAdjustType() == ADJUST_TYPE_FIXED) {
                                        BigDecimal amount = off.getAmount() == null ? BigDecimal.ZERO : off.getAmount();
                                        zyof3.setAddSize(amount.toString() + " " + "HKD");
                                    } else if (off.getAdjustType() == ADJUST_TYPE_PERCENT && off.getPercent() != null) {
                                        //加幅类型是百分比
                                        zyof3.setAddSize(off.getPercent().toString() + "%");
                                    }
                                    offlineCanalListDTOList.add(zyof3);
                                }
                                break;
                        }
                        break;
                    case 2:
                        //代理商
                        QueryWrapper<ScenicProductChannelOfflineAgentCustom> agentCustomquer = new QueryWrapper<>();
                        agentCustomquer.eq("is_deleted", 0);
                        agentCustomquer.eq("product_id", scenicProductReq.getProductId());
                        agentCustomquer.eq("offline_id", offline.getId());
                        List<ScenicProductChannelOfflineAgentCustom> agentCustomList = scenicProductChannelOfflineAgentCustomMapper.selectList(agentCustomquer);
                        switch (offline.getVisableType()) {
                            case 2://全部代理商
                                ScenicProductChannelOfflineAgentCustom agentCustom2 = agentCustomList.get(0);
                                OfflineCanalListDTO dl2 = new OfflineCanalListDTO();
                                dl2.setCanal("线下代理渠道-所有");
                                if (Objects.isNull(agentCustom2.getIsLimit()) || agentCustom2.getIsLimit() == 0) {
                                    dl2.setLimitNum("無限制");
                                } else {
                                    dl2.setLimitNum(agentCustom2.getLimitNum().toString());
                                }
                                if (Objects.isNull(agentCustom2.getAdjustType()) ||
                                        agentCustom2.getAdjustType() == ADJUST_TYPE_FIXED) {
                                    BigDecimal amount = agentCustom2.getAmount() == null ? BigDecimal.ZERO : agentCustom2.getAmount();
                                    dl2.setAddSize(amount.toString() + " " + "HKD");
                                } else if (agentCustom2.getAdjustType() == ADJUST_TYPE_PERCENT && agentCustom2.getPercent() != null) {
                                    //加幅类型是百分比
                                    dl2.setAddSize(agentCustom2.getPercent().toString() + "%");
                                }
                                offlineCanalListDTOList.add(dl2);
                                break;
                            case 3://指定代理商
                                for (ScenicProductChannelOfflineAgentCustom agentCustom3 : agentCustomList) {
                                    OfflineCanalListDTO dl3 = new OfflineCanalListDTO();
                                    dl3.setCanal("线下代理渠道-" + agentCustom3.getAgentName());
                                    if (Objects.isNull(agentCustom3.getIsLimit()) || agentCustom3.getIsLimit() == 0) {
                                        dl3.setLimitNum("無限制");
                                    } else {
                                        dl3.setLimitNum(agentCustom3.getLimitNum().toString());
                                    }
                                    if (Objects.isNull(agentCustom3.getAdjustType()) ||
                                            agentCustom3.getAdjustType() == ADJUST_TYPE_FIXED) {
                                        BigDecimal amount = agentCustom3.getAmount() == null ? BigDecimal.ZERO : agentCustom3.getAmount();
                                        dl3.setAddSize(amount.toString() + " " + "HKD");
                                    } else if (agentCustom3.getAdjustType() == ADJUST_TYPE_PERCENT && agentCustom3.getPercent() != null) {
                                        //加幅类型是百分比
                                        dl3.setAddSize(agentCustom3.getPercent().toString() + "%");
                                    }
                                    offlineCanalListDTOList.add(dl3);
                                }
                                break;
                        }
                        break;
                }
            }
            QueryWrapper<ScenicProductChannelOnlineSelfPlatform> platformQueryWrapper = new QueryWrapper<>();
            platformQueryWrapper.eq("is_deleted", 0);
            platformQueryWrapper.eq("strategy_id", strategy.getId());
            List<ScenicProductChannelOnlineSelfPlatform> selfPlatformList = scenicProductChannelOnlineSelfPlatformMapper.selectList(platformQueryWrapper);
            //綫上自營
            for (ScenicProductChannelOnlineSelfPlatform selfPlatform : selfPlatformList) {
                OnlineSelfListDTO zy = new OnlineSelfListDTO();
                zy.setCanal("线上官方渠道-" + selfPlatform.getChannelName());
                if (Objects.isNull(selfPlatform.getIsLimit()) || selfPlatform.getIsLimit() == 0) {
                    zy.setLimitNum("無限制");
                } else {
                    zy.setLimitNum(selfPlatform.getLimitNum().toString());
                }
                if (Objects.isNull(selfPlatform.getAdjustType()) ||
                        selfPlatform.getAdjustType() == ADJUST_TYPE_FIXED) {
                    BigDecimal amount = selfPlatform.getAmount() == null ? BigDecimal.ZERO : selfPlatform.getAmount();
                    zy.setAddSize(amount.toString() + " " + "HKD");
                } else if (selfPlatform.getAdjustType() == ADJUST_TYPE_PERCENT && selfPlatform.getPercent() != null) {
                    //加幅类型是百分比
                    zy.setAddSize(selfPlatform.getPercent().toString() + "%");
                }
                onlineSelfListDTOList.add(zy);
            }
            QueryWrapper<ScenicProductChannelOnlineThirdPlatform> thirdPlatformQueryWrapper = new QueryWrapper<>();
            thirdPlatformQueryWrapper.eq("is_deleted", 0);
            thirdPlatformQueryWrapper.eq("strategy_id", strategy.getId());
            //綫上第三方
            List<ScenicProductChannelOnlineThirdPlatform> thirdPlatformList = scenicProductChannelOnlineThirdPlatformMapper.selectList(thirdPlatformQueryWrapper);
            for (ScenicProductChannelOnlineThirdPlatform thirdPlatform : thirdPlatformList) {
                OnlineSelfListDTO dsf = new OnlineSelfListDTO();
                dsf.setCanal("线上三方渠道-" + thirdPlatform.getPlatformName());
                if (Objects.isNull(thirdPlatform.getIsLimit()) || thirdPlatform.getIsLimit() == 0) {
                    dsf.setLimitNum("無限制");
                } else {
                    dsf.setLimitNum(thirdPlatform.getLimitNum().toString());
                }
                if (Objects.isNull(thirdPlatform.getAdjustType()) ||
                        thirdPlatform.getAdjustType() == ADJUST_TYPE_FIXED) {
                    BigDecimal amount = thirdPlatform.getAmount() == null ? BigDecimal.ZERO : thirdPlatform.getAmount();
                    dsf.setAddSize(amount.toString() + " " + "HKD");
                } else if (thirdPlatform.getAdjustType() == ADJUST_TYPE_PERCENT && thirdPlatform.getPercent() != null) {
                    //加幅类型是百分比
                    dsf.setAddSize(thirdPlatform.getPercent().toString() + "%");
                }
                onlineSelfListDTOList.add(dsf);
            }
            Map<LocalDate, VaildDateDTO> map = new HashMap<>();
            QueryWrapper<ScenicProductSaleStrategyVaildDate> vaildDateQuery = new QueryWrapper<>();
            vaildDateQuery.eq("strategy_id", strategy.getId());
            List<ScenicProductSaleStrategyVaildDate> vaildDates = scenicProductSaleStrategyVaildDateMapper.selectList(vaildDateQuery);
            for (ScenicProductSaleStrategyVaildDate strategyDate : vaildDates) {
                long diffDay = strategyDate.getTimeEnd().toEpochDay() - strategyDate.getTimeBegin().toEpochDay();
                for (int i = 0; i <= diffDay; i++) {
                    LocalDate localDate = strategyDate.getTimeBegin().plusDays(i);

                    if (localDate.isBefore(startDate)) {
                        continue;
                    }
                    if (!localDate.isBefore(endDate)) {
                        continue;
                    }

                    VaildDateDTO ruleDto = new VaildDateDTO();
                    dateDTOList.add(ruleDto);
                    ruleDto.setOfflineCanalListDTOList(offlineCanalListDTOList);
                    ruleDto.setOnlineSelfListDTOList(onlineSelfListDTOList);
                    ruleDto.setDate(DateUtil.fmtLocalDate(localDate, DateUtil.fmt_day));
                }
            }
        }
        scenicProductDetailDTO.setVaildDateDTOList(dateDTOList);
        return Result.success(scenicProductDetailDTO);
    }

    @Override
    public Result<List<ScenicProductSaleStrategyDTO>> scenicProductEditDetai(ScenicProductEditReq scenicProductEditReq) {
        List<ScenicProductSaleStrategyDTO> saleStrategyDTOS = new ArrayList<>();
        QueryWrapper<ScenicProductSaleStrategy> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", scenicProductEditReq.getId());
        queryWrapper.eq("is_deleted", "0");
        List<ScenicProductSaleStrategy> scenicProductSaleStrategies = scenicProductSaleStrategyMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(scenicProductSaleStrategies)) {
            for (ScenicProductSaleStrategy scenicProductSaleStrategy : scenicProductSaleStrategies) {
                ScenicProductSaleStrategyDTO scenicProductSaleStrategyDTO = new ScenicProductSaleStrategyDTO();
                scenicProductSaleStrategyDTO.setName(scenicProductSaleStrategy.getName());
                QueryWrapper<ScenicProductSaleStrategyVaildDate> vaildDateQueryWrapper = new QueryWrapper<>();
                vaildDateQueryWrapper.eq("strategy_id", scenicProductSaleStrategy.getId());
                List<ScenicProductSaleStrategyVaildDate> list = scenicProductSaleStrategyVaildDateMapper.selectList(vaildDateQueryWrapper);
                List<ScenicTimeDTO> timeDTOList = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(list)) {
                    for (ScenicProductSaleStrategyVaildDate vaildDate : list) {
                        ScenicTimeDTO scenicTimeDTO = new ScenicTimeDTO();
                        scenicTimeDTO.setBeginTime(vaildDate.getTimeBegin());
                        scenicTimeDTO.setEndTime(vaildDate.getTimeEnd());
                        timeDTOList.add(scenicTimeDTO);
                    }
                }
                scenicProductSaleStrategyDTO.setTime(timeDTOList);
                //查询线下渠道
                ChannelSaleDTO channelSaleDTO = new ChannelSaleDTO();
                ScenicProductOfflineChannelDTO scenicProductOfflineChannelDTO = new ScenicProductOfflineChannelDTO();
                //自营渠道
                QueryWrapper<ScenicProductChannelOffline> offlineQueryWrapper = new QueryWrapper<>();
                offlineQueryWrapper.eq("product_id", scenicProductSaleStrategy.getProductId());
                offlineQueryWrapper.eq("strategy_id", scenicProductSaleStrategy.getId());
                List<ScenicProductChannelOffline> offlineList = scenicProductChannelOfflineMapper.selectList(offlineQueryWrapper);
                if (CollectionUtils.isNotEmpty(offlineList)) {
                    for (ScenicProductChannelOffline scenicProductChannelOffline : offlineList) {
                        //查詢线下集合  1是自营渠道  2是线下渠道
                        switch (scenicProductChannelOffline.getChannelType()) {
                            case 1:
                                //查询自营渠道的权限定义
                                switch (scenicProductChannelOffline.getVisableType()) {
                                    case 1:
                                        scenicProductOfflineChannelDTO.setVisableType(1);
                                        break;
                                    case 2:
                                        QueryWrapper<ScenicProductChannelOfflineSelfCustom> selfCustomQueryWrapper = new QueryWrapper<>();
                                        selfCustomQueryWrapper.eq("product_id", scenicProductSaleStrategy.getProductId());
                                        selfCustomQueryWrapper.eq("offline_id", scenicProductChannelOffline.getId());
                                        ScenicProductChannelOfflineSelfCustom selfCustom = scenicProductChannelOfflineSelfCustomMapper.selectOne(selfCustomQueryWrapper);
                                        if (selfCustom != null) {
                                            scenicProductOfflineChannelDTO = EntityUtil.copy(selfCustom, ScenicProductOfflineChannelDTO.class);
                                            scenicProductOfflineChannelDTO.setVisableType(scenicProductChannelOffline.getVisableType());
                                        }
                                        break;
                                    case 3:
                                        scenicProductOfflineChannelDTO.setVisableType(scenicProductChannelOffline.getVisableType());
                                        List<ScenicProductChannelOfflineSelfCustomDTO> scenicProductChannelOfflineSelfCustomDTOList = new ArrayList<>();
                                        QueryWrapper<ScenicProductChannelOfflineSelfCustom> selfCustomQueryWrapper1 = new QueryWrapper<>();
                                        selfCustomQueryWrapper1.eq("product_id", scenicProductSaleStrategy.getProductId());
                                        selfCustomQueryWrapper1.eq("offline_id", scenicProductChannelOffline.getId());
                                        selfCustomQueryWrapper1.eq("is_deleted", 0);
                                        List<ScenicProductChannelOfflineSelfCustom> selfCustoms = scenicProductChannelOfflineSelfCustomMapper.selectList(selfCustomQueryWrapper1);
                                        if (CollectionUtils.isNotEmpty(selfCustoms)) {
                                            for (ScenicProductChannelOfflineSelfCustom e : selfCustoms) {
                                                ScenicProductChannelOfflineSelfCustomDTO scenicProductChannelOfflineSelfCustomDTO = EntityUtil.copy(e, ScenicProductChannelOfflineSelfCustomDTO.class);
                                                scenicProductChannelOfflineSelfCustomDTOList.add(scenicProductChannelOfflineSelfCustomDTO);
                                                scenicProductOfflineChannelDTO.setScenicProductChannelOfflineSelfCustomDTOList(scenicProductChannelOfflineSelfCustomDTOList);
                                            }
                                        }
                                        break;
                                }
                                channelSaleDTO.setScenicProductOfflineChannelDTO(scenicProductOfflineChannelDTO);
                                break;
                            case 2:
                                //查询代理商的权限定义
                                ScenicProductAgentDTO scenicProductAgentDTO = new ScenicProductAgentDTO();
                                switch (scenicProductChannelOffline.getVisableType()) {
                                    case 1:
                                        scenicProductAgentDTO.setVisableType(1);
                                        break;
                                    case 2:
                                        QueryWrapper<ScenicProductChannelOfflineAgentCustom> customQueryWrapper = new QueryWrapper<>();
                                        customQueryWrapper.eq("product_id", scenicProductSaleStrategy.getProductId());
                                        customQueryWrapper.eq("offline_id", scenicProductChannelOffline.getId());
                                        customQueryWrapper.eq("is_deleted", 0);
                                        ScenicProductChannelOfflineAgentCustom agentCustom = scenicProductChannelOfflineAgentCustomMapper.selectOne(customQueryWrapper);
                                        if (null != agentCustom) {
                                            scenicProductAgentDTO = EntityUtil.copy(agentCustom, ScenicProductAgentDTO.class);
                                            scenicProductAgentDTO.setVisableType(scenicProductChannelOffline.getChannelType());
                                        }
                                        break;
                                    case 3:
                                        List<ScenicProductChannelOfflineAgentCustomDTO> scenicProductChannelOfflineAgentCustomDTOList = new ArrayList<>();
                                        QueryWrapper<ScenicProductChannelOfflineAgentCustom> customQueryWrapper1 = new QueryWrapper<>();
                                        customQueryWrapper1.eq("product_id", scenicProductSaleStrategy.getProductId());
                                        customQueryWrapper1.eq("offline_id", scenicProductChannelOffline.getId());
                                        customQueryWrapper1.eq("is_deleted", 0);
                                        List<ScenicProductChannelOfflineAgentCustom> agentCustomList = scenicProductChannelOfflineAgentCustomMapper.selectList(customQueryWrapper1);
                                        if (CollectionUtils.isNotEmpty(agentCustomList)) {
                                            for (ScenicProductChannelOfflineAgentCustom e : agentCustomList) {
                                                ScenicProductChannelOfflineAgentCustomDTO agentCustomDTO = EntityUtil.copy(e, ScenicProductChannelOfflineAgentCustomDTO.class);
                                                scenicProductChannelOfflineAgentCustomDTOList.add(agentCustomDTO);
                                            }
                                            scenicProductAgentDTO.setScenicProductChannelOfflineAgentCustomDTOList(scenicProductChannelOfflineAgentCustomDTOList);
                                        }
                                        break;
                                }
                                channelSaleDTO.setScenicProductAgentDTO(scenicProductAgentDTO);
                                break;
                        }
                    }
                }
                //线上官方平台
                List<ScenicProductChannelOnlineSelfPlatformDTO> scenicProductChannelOnlineSelfPlatformDTOList = new ArrayList<>();
                QueryWrapper<ScenicProductChannelOnlineSelfPlatform> platformQueryWrapper = new QueryWrapper<>();
                platformQueryWrapper.eq("is_deleted", 0);
                platformQueryWrapper.eq("strategy_id", scenicProductSaleStrategy.getId());
                List<ScenicProductChannelOnlineSelfPlatform> selfPlatformList = scenicProductChannelOnlineSelfPlatformMapper.selectList(platformQueryWrapper);
                if (CollectionUtils.isNotEmpty(selfPlatformList)) {
                    for (ScenicProductChannelOnlineSelfPlatform selfPlatform : selfPlatformList) {
                        ScenicProductChannelOnlineSelfPlatformDTO selfPlatformDTO = EntityUtil.copy(selfPlatform, ScenicProductChannelOnlineSelfPlatformDTO.class);
                        scenicProductChannelOnlineSelfPlatformDTOList.add(selfPlatformDTO);
                    }
                    channelSaleDTO.setScenicProductChannelOnlineSelfPlatformDTOList(scenicProductChannelOnlineSelfPlatformDTOList);
                }
                //第三方平台
                List<ScenicProductChannelOnlineThirdPlatformDTO> scenicProductChannelOnlineThirdPlatformDTOList = new ArrayList<>();
                QueryWrapper<ScenicProductChannelOnlineThirdPlatform> scenicProductChannelOnlineThirdPlatformQueryWrapper = new QueryWrapper();
                scenicProductChannelOnlineThirdPlatformQueryWrapper.eq("strategy_id", scenicProductSaleStrategy.getId());
                List<ScenicProductChannelOnlineThirdPlatform> platforms = scenicProductChannelOnlineThirdPlatformMapper.selectList(scenicProductChannelOnlineThirdPlatformQueryWrapper);
                if (CollectionUtils.isNotEmpty(platforms)) {
                    for (ScenicProductChannelOnlineThirdPlatform selfPlatform : platforms) {
                        ScenicProductChannelOnlineThirdPlatformDTO scenicProductChannelOnlineThirdPlatformDTO = EntityUtil.copy(selfPlatform, ScenicProductChannelOnlineThirdPlatformDTO.class);
                        scenicProductChannelOnlineThirdPlatformDTOList.add(scenicProductChannelOnlineThirdPlatformDTO);
                    }
                    channelSaleDTO.setScenicProductChannelOnlineThirdPlatformDTOList(scenicProductChannelOnlineThirdPlatformDTOList);
                }
                scenicProductSaleStrategyDTO.setChannelSaleDTO(channelSaleDTO);
                saleStrategyDTOS.add(scenicProductSaleStrategyDTO);
            }
        }
        return Result.success(saleStrategyDTOS);
    }

    @Override
    @Transactional
    public Result scenicProductEdit(ScenicProductBatchSaleStrategyReq req, TokenUser currentUser) {
        Long userId = currentUser == null ? null : currentUser.getId();
        QueryWrapper<ScenicProductSaleStrategy> strategyQueryWrapper = new QueryWrapper<>();
        strategyQueryWrapper.eq("is_deleted", 0);
        strategyQueryWrapper.eq("product_id", req.getScenicProductIdList().get(0));
        List<ScenicProductSaleStrategy> strategyList = scenicProductSaleStrategyMapper.selectList(strategyQueryWrapper);
        if (CollectionUtils.isNotEmpty(strategyList)) {
            //清空策略
            scenicProductSaleStrategyMapper.clearByProductId(req.getScenicProductIdList().get(0), currentUser.getId());
            //清空有效期
            scenicProductSaleStrategyVaildDateMapper.clearByProductId(req.getScenicProductIdList().get(0), currentUser.getId());
            //清空门票产品线下渠道权限范围表
            scenicProductChannelOfflineMapper.clearByProductId(req.getScenicProductIdList().get(0), currentUser.getId());
            //清空门票线下自营自定义权限
            scenicProductChannelOfflineSelfCustomMapper.clearByProductId(req.getScenicProductIdList().get(0));
            //清空门票线下代理商自定义权限
            scenicProductChannelOfflineAgentCustomMapper.clearByProductId(req.getScenicProductIdList().get(0), currentUser.getId());
            //清空门票线上渠道第三方平台
            scenicProductChannelOnlineThirdPlatformMapper.clearByProductId(req.getScenicProductIdList().get(0), currentUser.getId());
            //清空门票线上自营自定义权限
            scenicProductChannelOnlineSelfPlatformMapper.clearByProductId(req.getScenicProductIdList().get(0), currentUser.getId());
        }
        if (req.getScenicProductIdList() != null && req.getScenicProductIdList().size() >= 1) {
            Long productId = req.getScenicProductIdList().get(0);
            List<ScenicProductSaleStrategyReq> strategyReqlist = req.getStrategyList();
            if (strategyList != null && strategyList.size() >= 1) {
                for (ScenicProductSaleStrategyReq scenicProductSaleStrategyReq : strategyReqlist) {
                    //新增门票销售加幅策略
                    Long id = SnowflakeIdWorker.nextId();
                    ScenicProductSaleStrategy scenicProductSaleStrategy = new ScenicProductSaleStrategy();
                    scenicProductSaleStrategy.setId(id);
                    scenicProductSaleStrategy.setCreateId(userId);
                    scenicProductSaleStrategy.setIsDeleted(0);
                    scenicProductSaleStrategy.setGmtCreate(LocalDateTime.now());
                    scenicProductSaleStrategy.setProductId(productId);
                    scenicProductSaleStrategy.setName(scenicProductSaleStrategyReq.getName());
                    scenicProductSaleStrategyMapper.insert(scenicProductSaleStrategy);
                    //新增门票销售价格加幅有效期
                    List<ScenicTimeDTO> time = scenicProductSaleStrategyReq.getTime();
                    if (time != null && time.size() >= 1) {
                        List<ScenicProductSaleStrategyVaildDate> list = new ArrayList<>();
                        for (ScenicTimeDTO scenicTimeDTO : time) {
                            ScenicProductSaleStrategyVaildDate scenicProductSaleStrategyVaildDate = new ScenicProductSaleStrategyVaildDate();
                            scenicProductSaleStrategyVaildDate.setProductId(productId);
                            scenicProductSaleStrategyVaildDate.setGmtCreate(LocalDateTime.now());
                            scenicProductSaleStrategyVaildDate.setTimeBegin(scenicTimeDTO.getBeginTime());
                            scenicProductSaleStrategyVaildDate.setTimeEnd(scenicTimeDTO.getEndTime());
                            scenicProductSaleStrategyVaildDate.setStrategyId(id);
                            list.add(scenicProductSaleStrategyVaildDate);
                        }
                        scenicProductSaleStrategyVaildDateMapper.insertBatchSomeColumn(list);
                    }
                    ChannelSaleReq channelSaleReq = scenicProductSaleStrategyReq.getChannelSaleReq();
                    //新增线下渠道
                    ScenicProductOfflineChannelReq scenicProductOfflineChannelReq = channelSaleReq.getScenicProductOfflineChannelReq();
                    if (scenicProductOfflineChannelReq != null) {
                        Long officeId = SnowflakeIdWorker.nextId();
                        ScenicProductChannelOfflineSelfCustom scenicProductChannelOfflineSelfCustom = new ScenicProductChannelOfflineSelfCustom();
                        scenicProductChannelOfflineSelfCustom.setId(SnowflakeIdWorker.nextId());
                        scenicProductChannelOfflineSelfCustom.setProductId(productId);
                        scenicProductChannelOfflineSelfCustom.setGmtCreate(LocalDateTime.now());
                        scenicProductChannelOfflineSelfCustom.setCreateId(userId);
                        scenicProductChannelOfflineSelfCustom.setOfflineId(officeId);
                        scenicProductChannelOfflineSelfCustom.setIsDeleted(0);
                        ScenicProductChannelOffline scenicProductChannelOffline = new ScenicProductChannelOffline();
                        scenicProductChannelOffline.setProductId(productId);
                        scenicProductChannelOffline.setChannelType(1);
                        scenicProductChannelOffline.setCreateId(userId);
                        scenicProductChannelOffline.setGmtCreate(LocalDateTime.now());
                        scenicProductChannelOffline.setIsDeleted(0);
                        scenicProductChannelOffline.setStrategyId(id);
                        scenicProductChannelOffline.setId(officeId);
                        switch (scenicProductOfflineChannelReq.getVisableType()) {
                            case 1:
                                scenicProductChannelOffline.setVisableType(1);
                                scenicProductChannelOfflineMapper.insert(scenicProductChannelOffline);
                                break;
                            case 2:
                                scenicProductChannelOffline.setVisableType(2);
                                scenicProductChannelOfflineMapper.insert(scenicProductChannelOffline);
                                if (scenicProductOfflineChannelReq.getAdjustType() == ADJUST_TYPE_FIXED) {
                                    scenicProductChannelOfflineSelfCustom.setAdjustType(ADJUST_TYPE_FIXED);
                                    scenicProductChannelOfflineSelfCustom.setAmount(scenicProductOfflineChannelReq.getAmount());
                                } else if (scenicProductOfflineChannelReq.getAdjustType() == ADJUST_TYPE_PERCENT) {
                                    scenicProductChannelOfflineSelfCustom.setAdjustType(ADJUST_TYPE_PERCENT);
                                    scenicProductChannelOfflineSelfCustom.setPercent(scenicProductOfflineChannelReq.getPercent());
                                } else {
                                    break;
                                }
                                if (scenicProductOfflineChannelReq.getIsLimit() == 0) {
                                    scenicProductChannelOfflineSelfCustom.setIsLimit(0);
                                } else if (scenicProductOfflineChannelReq.getIsLimit() == 1) {
                                    scenicProductChannelOfflineSelfCustom.setIsLimit(1);
                                    scenicProductChannelOfflineSelfCustom.setLimitNum(scenicProductOfflineChannelReq.getLimitNum());
                                }
                                scenicProductChannelOfflineSelfCustomMapper.insert(scenicProductChannelOfflineSelfCustom);
                                break;
                            case 3:
                                scenicProductChannelOffline.setVisableType(3);
                                scenicProductChannelOfflineMapper.insert(scenicProductChannelOffline);
                                List<ScenicProductChannelOfflineSelfCustomReq> scenicProductChannelOfflineSelfCustomReqList = scenicProductOfflineChannelReq.getScenicProductChannelOfflineSelfCustomReqList();
                                if (scenicProductChannelOfflineSelfCustomReqList != null) {
                                    for (ScenicProductChannelOfflineSelfCustomReq customReq : scenicProductChannelOfflineSelfCustomReqList) {
                                        scenicProductChannelOfflineSelfCustom.setCheckType(customReq.getCheckType());
                                        scenicProductChannelOfflineSelfCustom.setName(customReq.getName());
                                        scenicProductChannelOfflineSelfCustom.setRelationId(customReq.getRelationId());
                                        if (scenicProductOfflineChannelReq.getAdjustType() == ADJUST_TYPE_FIXED) {
                                            scenicProductChannelOfflineSelfCustom.setAdjustType(ADJUST_TYPE_FIXED);
                                            scenicProductChannelOfflineSelfCustom.setAmount(scenicProductOfflineChannelReq.getAmount());
                                        } else if (scenicProductOfflineChannelReq.getAdjustType() == ADJUST_TYPE_PERCENT) {
                                            scenicProductChannelOfflineSelfCustom.setAdjustType(ADJUST_TYPE_PERCENT);
                                            scenicProductChannelOfflineSelfCustom.setPercent(scenicProductOfflineChannelReq.getPercent());
                                        } else {
                                            break;
                                        }
                                        if (scenicProductOfflineChannelReq.getIsLimit() == 0) {
                                            scenicProductChannelOfflineSelfCustom.setIsLimit(0);
                                        } else if (scenicProductOfflineChannelReq.getIsLimit() == 1) {
                                            scenicProductChannelOfflineSelfCustom.setIsLimit(1);
                                            scenicProductChannelOfflineSelfCustom.setLimitNum(scenicProductOfflineChannelReq.getLimitNum());
                                        }
                                        scenicProductChannelOfflineSelfCustomMapper.insert(scenicProductChannelOfflineSelfCustom);
                                    }
                                }
                                break;
                            default:
                                break;
                        }

                    }
                    //新增代理商
                    ScenicProductAgentReq scenicProductAgentReq = channelSaleReq.getScenicProductAgentReq();
                    if (scenicProductAgentReq != null) {
                        Long offLineId = SnowflakeIdWorker.nextId();
                        ScenicProductChannelOffline scenicProductChannelOffline = new ScenicProductChannelOffline();
                        scenicProductChannelOffline.setProductId(productId);
                        scenicProductChannelOffline.setChannelType(2);
                        scenicProductChannelOffline.setCreateId(userId);
                        scenicProductChannelOffline.setIsDeleted(0);
                        scenicProductChannelOffline.setStrategyId(id);
                        scenicProductChannelOffline.setId(offLineId);
                        //代理商
                        ScenicProductChannelOfflineAgentCustom scenicProductChannelOfflineAgentCustom = new ScenicProductChannelOfflineAgentCustom();
                        scenicProductChannelOfflineAgentCustom.setProductId(productId);
                        scenicProductChannelOfflineAgentCustom.setGmtCreate(LocalDateTime.now());
                        scenicProductChannelOfflineAgentCustom.setCreateId(userId);
                        scenicProductChannelOfflineAgentCustom.setOfflineId(offLineId);
                        scenicProductChannelOfflineAgentCustom.setId(SnowflakeIdWorker.nextId());
                        switch (scenicProductAgentReq.getVisableType()) {
                            case 1:
                                scenicProductChannelOffline.setVisableType(1);
                                scenicProductChannelOfflineMapper.insert(scenicProductChannelOffline);
                                break;
                            case 2:
                                scenicProductChannelOffline.setVisableType(2);
                                scenicProductChannelOfflineMapper.insert(scenicProductChannelOffline);
                                if (scenicProductAgentReq.getAdjustType() == ADJUST_TYPE_FIXED) {
                                    scenicProductChannelOfflineAgentCustom.setAmount(scenicProductAgentReq.getAmount());
                                    scenicProductChannelOfflineAgentCustom.setAdjustType(ADJUST_TYPE_FIXED);
                                } else if (scenicProductAgentReq.getAdjustType() == ADJUST_TYPE_PERCENT) {
                                    scenicProductChannelOfflineAgentCustom.setAdjustType(ADJUST_TYPE_PERCENT);
                                    scenicProductChannelOfflineAgentCustom.setPercent(scenicProductAgentReq.getPercent());
                                } else {
                                    break;
                                }
                                if (scenicProductAgentReq.getIsLimit() == 0) {
                                    scenicProductChannelOfflineAgentCustom.setLimitNum(scenicProductAgentReq.getLimitNum());
                                } else if (scenicProductAgentReq.getIsLimit() == 1) {
                                    scenicProductChannelOfflineAgentCustom.setIsLimit(1);
                                    scenicProductChannelOfflineAgentCustom.setLimitNum(scenicProductAgentReq.getLimitNum());
                                }
                                scenicProductChannelOfflineAgentCustomMapper.insert(scenicProductChannelOfflineAgentCustom);
                                break;
                            case 3:
                                scenicProductChannelOffline.setVisableType(3);
                                scenicProductChannelOfflineMapper.insert(scenicProductChannelOffline);
                                List<ScenicProductChannelOfflineAgentCustomReq> scenicProductChannelOfflineAgentCustomReqList = scenicProductAgentReq.getScenicProductChannelOfflineAgentCustomReqList();
                                if (scenicProductChannelOfflineAgentCustomReqList != null) {
                                    for (ScenicProductChannelOfflineAgentCustomReq req1 : scenicProductChannelOfflineAgentCustomReqList) {
                                        scenicProductChannelOfflineAgentCustom.setAgentId(req1.getAgentId());
                                        scenicProductChannelOfflineAgentCustom.setAgentName(req1.getAgentName());
                                        if (req1.getAdjustType() == ADJUST_TYPE_FIXED) {
                                            scenicProductChannelOfflineAgentCustom.setAdjustType(ADJUST_TYPE_FIXED);
                                            scenicProductChannelOfflineAgentCustom.setAmount(req1.getAmount());
                                        } else if (req1.getAdjustType() == ADJUST_TYPE_PERCENT) {
                                            scenicProductChannelOfflineAgentCustom.setAdjustType(ADJUST_TYPE_PERCENT);
                                            scenicProductChannelOfflineAgentCustom.setPercent(req1.getPercent());
                                        } else {
                                            break;
                                        }
                                        if (req1.getIsLimit() == 0) {
                                            scenicProductChannelOfflineAgentCustom.setIsLimit(0);
                                        } else if (req1.getIsLimit() == 1) {
                                            scenicProductChannelOfflineAgentCustom.setIsLimit(1);
                                            scenicProductChannelOfflineAgentCustom.setLimitNum(req1.getLimitNum());
                                        }
                                        scenicProductChannelOfflineAgentCustomMapper.insert(scenicProductChannelOfflineAgentCustom);
                                    }
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    //新增线下渠道官方平台
                    List<ScenicProductChannelOnlineSelfPlatformReq> scenicProductChannelOnlineSelfPlatformReqList = channelSaleReq.getScenicProductChannelOnlineSelfPlatformReqList();
                    if (scenicProductChannelOnlineSelfPlatformReqList != null) {
                        for (ScenicProductChannelOnlineSelfPlatformReq req1 : scenicProductChannelOnlineSelfPlatformReqList) {
                            ScenicProductChannelOnlineSelfPlatform scenicProductChannelOnlineSelfPlatform = new ScenicProductChannelOnlineSelfPlatform();
                            scenicProductChannelOnlineSelfPlatform.setId(SnowflakeIdWorker.nextId());
                            scenicProductChannelOnlineSelfPlatform.setProductId(productId);
                            scenicProductChannelOnlineSelfPlatform.setCreateId(userId);
                            scenicProductChannelOnlineSelfPlatform.setIsDeleted(0);
                            scenicProductChannelOnlineSelfPlatform.setGmtCreate(LocalDateTime.now());
                            scenicProductChannelOnlineSelfPlatform.setChannelId(req1.getChannelId());
                            scenicProductChannelOnlineSelfPlatform.setChannelName(req1.getChannelName());
                            if (req1.getAdjustType() == ADJUST_TYPE_FIXED) {
                                scenicProductChannelOnlineSelfPlatform.setAdjustType(ADJUST_TYPE_FIXED);
                                scenicProductChannelOnlineSelfPlatform.setAmount(req1.getAmount());
                            } else if (req1.getAdjustType() == ADJUST_TYPE_PERCENT) {
                                scenicProductChannelOnlineSelfPlatform.setAdjustType(ADJUST_TYPE_PERCENT);
                                scenicProductChannelOnlineSelfPlatform.setPercent(req1.getPercent());
                            } else {
                                break;
                            }
                            if (req1.getIsLimit() == 0) {
                                scenicProductChannelOnlineSelfPlatform.setIsLimit(0);
                            } else if (req1.getIsLimit() == 1) {
                                scenicProductChannelOnlineSelfPlatform.setIsLimit(1);
                                scenicProductChannelOnlineSelfPlatform.setLimitNum(req1.getLimitNum());
                            }
                            scenicProductChannelOnlineSelfPlatformMapper.insert(scenicProductChannelOnlineSelfPlatform);
                        }
                    }
                    //新增线下渠道第三方平台
                    List<ScenicProductChannelOnlineThirdPlatformReq> scenicProductChannelOnlineThirdPlatformReqList = channelSaleReq.getScenicProductChannelOnlineThirdPlatformReqList();
                    if (scenicProductChannelOnlineThirdPlatformReqList != null) {
                        for (ScenicProductChannelOnlineThirdPlatformReq req1 : scenicProductChannelOnlineThirdPlatformReqList) {
                            ScenicProductChannelOnlineThirdPlatform scenicProductChannelOnlineThirdPlatform = new ScenicProductChannelOnlineThirdPlatform();
                            scenicProductChannelOnlineThirdPlatform.setProductId(productId);
                            scenicProductChannelOnlineThirdPlatform.setId(SnowflakeIdWorker.nextId());
                            scenicProductChannelOnlineThirdPlatform.setIsDeleted(0);
                            scenicProductChannelOnlineThirdPlatform.setCreateId(userId);
                            scenicProductChannelOnlineThirdPlatform.setPlatformId(req1.getPlatformId());
                            scenicProductChannelOnlineThirdPlatform.setPlatformName(req1.getPlatformName());
                            scenicProductChannelOnlineThirdPlatform.setGmtCreate(LocalDateTime.now());
                            if (req1.getAdjustType() == ADJUST_TYPE_FIXED) {
                                scenicProductChannelOnlineThirdPlatform.setAdjustType(ADJUST_TYPE_FIXED);
                                scenicProductChannelOnlineThirdPlatform.setAmount(req1.getAmount());
                            } else if (req1.getAdjustType() == ADJUST_TYPE_PERCENT) {
                                scenicProductChannelOnlineThirdPlatform.setAdjustType(ADJUST_TYPE_PERCENT);
                                scenicProductChannelOnlineThirdPlatform.setPercent(req1.getPercent());
                            } else {
                                break;
                            }
                            if (req1.getIsLimit() == 0) {
                                scenicProductChannelOnlineThirdPlatform.setIsLimit(0);
                            } else {
                                scenicProductChannelOnlineThirdPlatform.setIsLimit(1);
                                scenicProductChannelOnlineThirdPlatform.setLimitNum(req1.getLimitNum());
                            }
                            scenicProductChannelOnlineThirdPlatformMapper.insert(scenicProductChannelOnlineThirdPlatform);
                        }
                    }

                }
            }
        }
        return Result.success();
    }

    @Override
    public Result<List<ScenicProductListDTO>> scenicProductList(ScenicProductReq scenicProductReq) {
        QueryWrapper<ScenicProduct> scenicProductQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(scenicProductReq.getCityId())) {
            scenicProductQueryWrapper.eq("city_id", scenicProductReq.getCityId());
            scenicProductQueryWrapper.eq("is_deleted", 0);
        }
        if (StringUtils.isNotBlank(scenicProductReq.getScenicId())) {
            scenicProductQueryWrapper.eq("scenic_id", scenicProductReq.getScenicId());
            scenicProductQueryWrapper.eq("is_deleted", 0);
        }
        List<ScenicProduct> list = scenicProductMapper.selectList(scenicProductQueryWrapper);
        List<ScenicProductListDTO> scenicProductListDTOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (ScenicProduct scenicProduct : list) {
                ScenicProductListDTO scenicProductListDTO = EntityUtil.copy(scenicProduct, ScenicProductListDTO.class);
                scenicProductListDTOS.add(scenicProductListDTO);
            }
        }
        return Result.success(scenicProductListDTOS);
    }

    @Override
    public Result<ScenicProductTicketDTO> scenicProductTicketPrice(ScenicProductTicketReq scenicProductTicketReq) {
        ScenicProductTicketDTO scenicProductTicketDTO = new ScenicProductTicketDTO();
        QueryWrapper<ScenicProduct> scenicProductQueryWrapper = new QueryWrapper<>();
        scenicProductQueryWrapper.eq("is_deleted", 0);
        scenicProductQueryWrapper.eq("id", scenicProductTicketReq.getProductId());
        ScenicProduct scenicProduct = scenicProductMapper.selectOne(scenicProductQueryWrapper);
        if (scenicProduct != null) {
            ScenicOrderDetailReq req = new ScenicOrderDetailReq();
            req.setOrderId(scenicProductTicketReq.getOrderId().toString());
            Result<ScenicOrderDetailDTO> result = scenicOrderService.scenicOrderDetail(req);
            if ("1".equals(scenicProduct.getReserveChargeType())) {
                scenicProductTicketDTO.setCharge(scenicProduct.getReserveCharge());
            }
            if (result.isSuccess() && result.getData() != null) {
                ScenicOrderDetailDTO scenicOrderDetailDTO = result.getData();
                if ("2".equals(scenicProduct.getReserveChargeType())) {
                    if (scenicOrderDetailDTO.getProductTicketNumber().intValue() > 0) {
                        BigDecimal reserveCharge = scenicOrderDetailDTO.getServiceFee().divide(new BigDecimal(scenicOrderDetailDTO.getProductTicketNumber().toString()));
                        scenicProductTicketDTO.setCharge(reserveCharge);
                    }
                }
                scenicProductTicketDTO.setCostPrice(scenicOrderDetailDTO.getSingleTicketFee());
            }
        }
        return Result.success(scenicProductTicketDTO);
    }

    @Override
    public Result<ScenicProductDetailByIdDTO> scenicProductDetailByIdDTO(ScenicProductDetailReq scenicProductDetailReq) {
        ScenicProduct scenicProduct = scenicProductMapper.selectById(scenicProductDetailReq.getId());
        ScenicProductDetailByIdDTO scenicProductDetailByIdDTO = new ScenicProductDetailByIdDTO();
        if (scenicProduct != null) {
            scenicProductDetailByIdDTO = EntityUtil.copy(scenicProduct, ScenicProductDetailByIdDTO.class);
        }
        return Result.success(scenicProductDetailByIdDTO);
    }

    @Override
    public Result<ScenicProductTicketDetailDTO> scenicProductTicketDetail(ScenicProductTicketDetailReq scenicProductTicketDetailReq) {
        ScenicProductTicketDetailDTO scenicProductTicketDetailDTO = new ScenicProductTicketDetailDTO();
        if (scenicProductTicketDetailReq.getId() != null) {
            ScenicProductTicket scenicProductTicket = scenicProductTicketMapper.selectById(scenicProductTicketDetailReq.getId());
            scenicProductTicketDetailDTO = new ScenicProductTicketDetailDTO();
            if (scenicProductTicket != null) {
                scenicProductTicketDetailDTO.setStockNumber(scenicProductTicket.getStockNumber());
                scenicProductTicketDetailDTO.setSupplierTicketNumber(scenicProductTicket.getSupplierTicketNumber());
                scenicProductTicketDetailDTO.setProductId(scenicProductTicket.getProductId().toString());
            }
        }
        return Result.success(scenicProductTicketDetailDTO);
    }

    @Override
    public Result modifyProductTicket(List<ScenicProductTicketListReq> scenicProductTicketListReqList, TokenUser tokenUser) {
        if (CollectionUtils.isNotEmpty(scenicProductTicketListReqList)) {
            for (ScenicProductTicketListReq scenicProductTicketListReq : scenicProductTicketListReqList) {
                ScenicProductTicket scenicProductTicket = scenicProductTicketMapper.selectById(scenicProductTicketListReq.getTicketsProductId());
                if (scenicProductTicketListReq.getSupplierTicketNumber() != null) {
                    scenicProductTicket.setSupplierTicketNumber(scenicProductTicketListReq.getSupplierTicketNumber());
                }
                scenicProductTicket.setGmtModified(LocalDateTime.now());
                scenicProductTicket.setModifiedId(tokenUser.getId());
                scenicProductTicketMapper.updateById(scenicProductTicket);
            }
        }
        return Result.success();
    }

    @Override
    public Result<ScenicProductReceiptDTO> scenicProductDetail(ScenicProductDetailReq scenicProductDetailReq) {
        ScenicProduct scenicProduct = scenicProductMapper.selectById(scenicProductDetailReq.getId());
        ScenicProductReceiptDTO scenicProductReceiptDTO = EntityUtil.copy(scenicProduct, ScenicProductReceiptDTO.class);
        //成本价
        String productTicketsIds = scenicProductDetailReq.getProductTicketsId();
        String productTicketsId = null;
        if (productTicketsIds != null) {
            if (productTicketsIds.contains(",")) {
                scenicProductReceiptDTO.setQuantity(productTicketsIds.split(",").length);
                productTicketsId = productTicketsIds.substring(0, productTicketsIds.indexOf(","));
            } else {
                scenicProductReceiptDTO.setQuantity(1);
                productTicketsId = productTicketsIds;
            }
        }
        ScenicProductTicket scenicProductTicket = scenicProductTicketMapper.selectById(productTicketsId);
        if (scenicProductTicket != null) {
            //规格属性
            List<ScenicProductSpecAttrDTO> scenicProductSpecAttrDTOList = new ArrayList<>();
            QueryWrapper<ScenicProductCostStrategySpecAttr> queryWrapper = new QueryWrapper();
            queryWrapper.eq("is_deleted", 0);
            queryWrapper.eq("product_id", scenicProduct.getId());
            List<ScenicProductCostStrategySpecAttr> list = scenicProductCostStrategySpecAttrMapper.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(list)) {
                for (ScenicProductCostStrategySpecAttr scenicProductCostStrategySpecAttr : list) {
                    if (scenicProductCostStrategySpecAttr.getSpecId() == scenicProductTicket.getAttr1Id()) {
                        ScenicProductSpecAttrDTO scenicProductSpecAttrDTO = new ScenicProductSpecAttrDTO();
                        scenicProductSpecAttrDTO.setSpecName(scenicProductCostStrategySpecAttr.getSpecName());
                        scenicProductSpecAttrDTO.setAttributeName(scenicProductTicket.getAttr1Name());
                        scenicProductSpecAttrDTOList.add(scenicProductSpecAttrDTO);
                    }
                    if (scenicProductCostStrategySpecAttr.getSpecId() == scenicProductTicket.getAttr2Id()) {
                        ScenicProductSpecAttrDTO scenicProductSpecAttrDTO = new ScenicProductSpecAttrDTO();
                        scenicProductSpecAttrDTO.setSpecName(scenicProductCostStrategySpecAttr.getSpecName());
                        scenicProductSpecAttrDTO.setAttributeName(scenicProductTicket.getAttr2Name());
                        scenicProductSpecAttrDTOList.add(scenicProductSpecAttrDTO);
                    }
                }
            }

        }
        return Result.success(scenicProductReceiptDTO);
    }

    @Override
    public List<ScenicProductPriceListDTO> scenicProductPriceList(ScenicProductPriceListReq scenicProductPriceListReq) {
        UserDTO userDTO = null;
        List<ScenicProductPriceListDTO> scenicProductPriceList = new ArrayList<>();
        List<ScenicProductPriceListDTO> scenicProductPriceListNew = new ArrayList<>();
        //先查加幅，如果没加幅，就没价格
        //根据产品id查出门票销售价格加幅有效期
        QueryWrapper<ScenicProductSaleStrategyVaildDate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", scenicProductPriceListReq.getProductId());
        List<ScenicProductSaleStrategyVaildDate> list = scenicProductSaleStrategyVaildDateMapper.selectList(queryWrapper);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            userDTO = iSysUserService.loadUserByParam(scenicProductPriceListReq.getUserId(), 1);
            Date dateCurrent = df.parse(DateUtil.fmtLocalDate(scenicProductPriceListReq.getTime(), "yyyy-MM-dd"));
            long timeCurrent = dateCurrent.getTime();
            List<String> times = new ArrayList<>();
            for (ScenicProductSaleStrategyVaildDate vaildDatedate : list) {
                Date dateBegin = df.parse(DateUtil.fmtLocalDate(vaildDatedate.getTimeBegin(), "yyyy-MM-dd"));
                long timeBegin = dateBegin.getTime();
                Date dateEnd = df.parse(DateUtil.fmtLocalDate(vaildDatedate.getTimeEnd(), "yyyy-MM-dd"));
                long timeEnd = dateEnd.getTime();
                times.add(String.valueOf(timeBegin));
                times.add(String.valueOf(timeEnd));
                if (timeCurrent == timeBegin || timeCurrent == timeEnd) {
                    scenicProductPriceList = scenicProductMapper.scenicProductPriceList(scenicProductPriceListReq);
                    if (CollectionUtils.isNotEmpty(scenicProductPriceList)) {
                        for (ScenicProductPriceListDTO scenicProductPriceListDTO : scenicProductPriceList) {
                            //查出产品
                            ScenicProduct scenicProduct = scenicProductMapper.selectById(scenicProductPriceListReq.getProductId());
                            if (scenicProduct != null && scenicProduct.getReserveChargeType() != null) {
                                //服务费
                                if (scenicProduct.getReserveChargeType() == 1) {
                                    scenicProductPriceListDTO.setReserveCharge(scenicProduct.getReserveCharge());
                                } else if (scenicProduct.getReserveChargeType() == 2) {
                                    scenicProductPriceListDTO.setReserveCharge(scenicProductPriceListDTO.getPrice().multiply(scenicProduct.getReserveCharge()).divide(new BigDecimal("100")));
                                }
                            }
                            QueryWrapper<ScenicProductChannelOffline> scenicProductChannelOfflineQueryWrapper = new QueryWrapper<>();
                            scenicProductChannelOfflineQueryWrapper.eq("product_id", scenicProductPriceListReq.getProductId());
                            scenicProductChannelOfflineQueryWrapper.eq("strategy_id", vaildDatedate.getStrategyId());
                            //自营渠道类型
                            scenicProductChannelOfflineQueryWrapper.eq("channel_type", 1);
                            List<ScenicProductChannelOffline> scenicProductChannelOfflineList = scenicProductChannelOfflineMapper.selectList(scenicProductChannelOfflineQueryWrapper);
                            if (CollectionUtils.isNotEmpty(scenicProductChannelOfflineList)) {
                                ScenicProductChannelOffline scenicProductChannelOffline = scenicProductChannelOfflineList.get(0);
                                QueryWrapper<ScenicProductChannelOfflineSelfCustom> customQueryWrapper = new QueryWrapper<>();
                                customQueryWrapper.eq("offline_id", scenicProductChannelOffline.getId());
                                customQueryWrapper.eq("product_id", scenicProductPriceListReq.getProductId());
                                List<ScenicProductChannelOfflineSelfCustom> customList = scenicProductChannelOfflineSelfCustomMapper.selectList(customQueryWrapper);
                                if (CollectionUtils.isNotEmpty(customList)) {
                                    ScenicProductChannelOfflineSelfCustom selfCustom = customList.get(0);
                                    if (scenicProductChannelOffline.getVisableType() != null && scenicProductChannelOffline.getVisableType() == 2) {
                                        if (selfCustom.getAdjustType() != null) {
                                            if (selfCustom.getAdjustType() == ADJUST_TYPE_FIXED && scenicProductPriceListDTO.getPrice() != null) {

                                                scenicProductPriceListDTO.setPrice(scenicProductPriceListDTO.getPrice().add(selfCustom.getAmount()));
                                            } else if (selfCustom.getAdjustType() == ADJUST_TYPE_PERCENT && selfCustom.getPercent() != null) {
                                                scenicProductPriceListDTO.setPrice(scenicProductPriceListDTO.getPrice().add(scenicProductPriceListDTO.getPrice().multiply(new BigDecimal(selfCustom.getPercent())).divide(new BigDecimal("100"))));
                                            }
                                        }
                                    } else if (scenicProductChannelOffline.getVisableType() != null && scenicProductChannelOffline.getVisableType() == 3) {
                                        //部门
                                        if (selfCustom.getCheckType() != null && selfCustom.getCheckType() == 1) {
                                            if (userDTO != null && userDTO.getDeptId().longValue() == selfCustom.getRelationId().longValue()) {
                                                if (selfCustom.getAdjustType() != null) {
                                                    if (selfCustom.getAdjustType() == ADJUST_TYPE_FIXED && scenicProductPriceListDTO.getPrice() != null) {
                                                        scenicProductPriceListDTO.setPrice(scenicProductPriceListDTO.getPrice().add(selfCustom.getAmount()));
                                                    } else if (selfCustom.getAdjustType() == ADJUST_TYPE_PERCENT && selfCustom.getPercent() != null) {
                                                        scenicProductPriceListDTO.setPrice(scenicProductPriceListDTO.getPrice().add(scenicProductPriceListDTO.getPrice().multiply(new BigDecimal(selfCustom.getPercent())).divide(new BigDecimal("100"))));
                                                    }
                                                }
                                            }   //人员
                                        } else if (selfCustom.getCheckType() != null && selfCustom.getCheckType() == 2) {
                                            if (userDTO != null && userDTO.getId().longValue() == selfCustom.getRelationId().longValue()) {
                                                if (selfCustom.getAdjustType() != null) {
                                                    if (selfCustom.getAdjustType() == ADJUST_TYPE_FIXED && scenicProductPriceListDTO.getPrice() != null) {
                                                        scenicProductPriceListDTO.setPrice(scenicProductPriceListDTO.getPrice().add(selfCustom.getAmount()));
                                                    } else if (selfCustom.getAdjustType() == ADJUST_TYPE_PERCENT && selfCustom.getPercent() != null) {
                                                        scenicProductPriceListDTO.setPrice(scenicProductPriceListDTO.getPrice().add(scenicProductPriceListDTO.getPrice().multiply(new BigDecimal(selfCustom.getPercent())).divide(new BigDecimal("100"))));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            scenicProductPriceListNew.add(scenicProductPriceListDTO);
                        }
                    }
                }
            }
            if (!times.contains(String.valueOf(timeCurrent))) {
                throw new BusinessException(SystemError.SCENIC_5002);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return scenicProductPriceListNew;
    }

    @Override
    public Result<ScenicProductPriceListDTO> scenicProductPriceDetail(ScenicProductPriceDetailReq scenicProductPriceDetailReq, TokenUser tokenUser) {
        ScenicProductPriceListDTO scenicProductPriceListDTO = scenicProductMapper.scenicProductPriceDetail(scenicProductPriceDetailReq);
        UserDTO userDTO = iSysUserService.loadUserByParam(tokenUser.getId(), 1);
        if (scenicProductPriceListDTO != null) {
            ScenicProduct scenicProduct = scenicProductMapper.selectById(scenicProductPriceDetailReq.getProductId());
            if (scenicProduct != null && scenicProduct.getReserveChargeType() != null) {
                if (scenicProduct.getReserveChargeType() == 1) {
                    scenicProductPriceListDTO.setPrice(scenicProductPriceListDTO.getPrice().add(scenicProduct.getReserveCharge()));
                } else if (scenicProduct.getReserveChargeType() == 2) {
                    scenicProductPriceListDTO.setPrice(scenicProductPriceListDTO.getPrice().add(scenicProductPriceListDTO.getPrice().multiply(scenicProduct.getCtsCharge()).divide(new BigDecimal("100"))));
                }
            }
            QueryWrapper<ScenicProductChannelOffline> scenicProductChannelOfflineQueryWrapper = new QueryWrapper<>();
            scenicProductChannelOfflineQueryWrapper.eq("product_id", scenicProductPriceDetailReq.getProductId());
            scenicProductChannelOfflineQueryWrapper.eq("strategy_id", scenicProductPriceListDTO.getStrategyId());
            //自营渠道类型
            scenicProductChannelOfflineQueryWrapper.eq("channel_type", 1);
            List<ScenicProductChannelOffline> scenicProductChannelOfflineList = scenicProductChannelOfflineMapper.selectList(scenicProductChannelOfflineQueryWrapper);
            if (CollectionUtils.isNotEmpty(scenicProductChannelOfflineList)) {
                ScenicProductChannelOffline scenicProductChannelOffline = scenicProductChannelOfflineList.get(0);
                QueryWrapper<ScenicProductChannelOfflineSelfCustom> customQueryWrapper = new QueryWrapper<>();
                customQueryWrapper.eq("offline_id", scenicProductChannelOffline.getId());
                customQueryWrapper.eq("product_id", scenicProductPriceDetailReq.getProductId());
                List<ScenicProductChannelOfflineSelfCustom> customList = scenicProductChannelOfflineSelfCustomMapper.selectList(customQueryWrapper);
                if (CollectionUtils.isNotEmpty(customList)) {
                    ScenicProductChannelOfflineSelfCustom selfCustom = customList.get(0);
                    if (scenicProductChannelOffline.getVisableType() != null) {
                        if (scenicProductChannelOffline.getVisableType() == 2) {
                            if (selfCustom.getAdjustType() != null) {
                                if (selfCustom.getAdjustType() == ADJUST_TYPE_FIXED && scenicProductPriceListDTO.getPrice() != null) {
                                    scenicProductPriceListDTO.setPrice(scenicProductPriceListDTO.getPrice().add(selfCustom.getAmount()));
                                } else if (selfCustom.getAdjustType() == ADJUST_TYPE_PERCENT && selfCustom.getPercent() != null) {
                                    scenicProductPriceListDTO.setPrice(scenicProductPriceListDTO.getPrice().add(scenicProductPriceListDTO.getPrice().multiply(new BigDecimal(selfCustom.getPercent())).divide(new BigDecimal("100"))));
                                }
                            }
                        } else if (scenicProductChannelOffline.getVisableType() == 3) {
                            //部门
                            if (selfCustom.getCheckType() == 1) {
                                if (userDTO != null && userDTO.getDeptId().longValue() == selfCustom.getRelationId().longValue()) {
                                    if (selfCustom.getAdjustType() != null) {
                                        if (selfCustom.getAdjustType() == ADJUST_TYPE_FIXED && scenicProductPriceListDTO.getPrice() != null) {
                                            scenicProductPriceListDTO.setPrice(scenicProductPriceListDTO.getPrice().add(selfCustom.getAmount()));
                                        } else if (selfCustom.getAdjustType() == ADJUST_TYPE_PERCENT && selfCustom.getPercent() != null) {
                                            scenicProductPriceListDTO.setPrice(scenicProductPriceListDTO.getPrice().add(scenicProductPriceListDTO.getPrice().multiply(new BigDecimal(selfCustom.getPercent())).divide(new BigDecimal("100"))));
                                        }
                                    }
                                }   //人员
                            } else if (selfCustom.getCheckType() == 2) {
                                if (userDTO != null && userDTO.getId().longValue() == selfCustom.getRelationId().longValue()) {
                                    if (selfCustom.getAdjustType() != null) {
                                        if (selfCustom.getAdjustType() == ADJUST_TYPE_FIXED && scenicProductPriceListDTO.getPrice() != null) {
                                            scenicProductPriceListDTO.setPrice(scenicProductPriceListDTO.getPrice().add(selfCustom.getAmount()));
                                        } else if (selfCustom.getAdjustType() == ADJUST_TYPE_PERCENT && selfCustom.getPercent() != null) {
                                            scenicProductPriceListDTO.setPrice(scenicProductPriceListDTO.getPrice().add(scenicProductPriceListDTO.getPrice().multiply(new BigDecimal(selfCustom.getPercent())).divide(new BigDecimal("100"))));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return Result.success(scenicProductPriceListDTO);
    }

    @Override
    public Result saveScenicProduct(TokenUser user) {
        String CONTENT_WITH_NO_SIGN = "{\"mer_no\":\"9000000242\",\"method\":\"chimelong.trip.product.info.get\",\"sign\":\"\",\"nonce_str\":\"80c5a87d22ed461bbe91ec691a4d9874\",\"timestamp\":\"2021-03-12 10:13:01\",\"ver_no\":\"1.0\",\"body\":\"{}}\"}";
        String signAppendStr = new APISignUtil().contentJointTest(CONTENT_WITH_NO_SIGN);
        String toData = new APIAesUtil().aesEncodeBase64(signAppendStr, "1d70b9997df4946824810ebb069dbe28");//SIGN_KEY:"1d70b9997df4946824810ebb069dbe28"（长隆提供）
        String params =
                "{" +
                        "\"mer_no\":\"9000000242\"," +
                        "\"data\":\"" + toData + "\"" +
                        "}";
        String contentType = "application/json;charset=utf-8";
        String path = "http://47.244.225.190:8080/hub/product/ota/call2/gsa/chimelong/api.do";
        String returnStr = new APIAesUtil().aesDecodeBase64(APIUtil.callAPIFunc(contentType, path, params, "POST"), "1d70b9997df4946824810ebb069dbe28");
        System.out.println(returnStr);
        cn.hutool.json.JSONObject j = new JSONObject(returnStr);
        JSONArray productData = j.getJSONObject("body").getJSONArray("productData");
        List<ChimeLongScenicProductDTO> chimeLongScenicProductDTOs = (List<ChimeLongScenicProductDTO>) JSON.parseArray(String.valueOf(productData), ChimeLongScenicProductDTO.class);
        for (ChimeLongScenicProductDTO scenicProductDTO : chimeLongScenicProductDTOs) {
            ScenicProduct scenicProduct = new ScenicProduct();
            if (scenicProductDTO.getParkCode() != null) {
                scenicProduct.setScenicId(Long.parseLong(scenicProductDTO.getParkCode()));
            }
            JSONObject jsonScenicProductName = new JSONObject(scenicProductDTO.getProductName());
            scenicProduct.setName(jsonScenicProductName.get("zh_TW").toString());
            scenicProduct.setProductCode(scenicProductDTO.getProductCode());
            scenicProduct.setGmtCreate(LocalDateTime.now());
            scenicProduct.setCreateId(user.getId());
            scenicProduct.setProductType(scenicProductDTO.getProductType());
            scenicProduct.setProductIntroduces(scenicProductDTO.getProductDesc());
            if (scenicProductDTO.getSellBegDate() != null) {
                scenicProduct.setStartSaleTimeType(2);
                LocalDateTime time = LocalDateTime.parse(scenicProductDTO.getSellBegDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                scenicProduct.setStartSaleTimeBegin(time);
                LocalDateTime timeEnd = LocalDateTime.parse(start_sale_time_end, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                scenicProduct.setStartSaleTimeEnd(timeEnd);
            } else {
                scenicProduct.setStartSaleTimeType(1);
            }
            scenicProduct.setSourceType(1);
            scenicProductMapper.insert(scenicProduct);

        }
        return Result.success();
    }

    @Override
    public Result saveScenicProductPrice(ChimeLongProductPriceAndStockReq req, TokenUser user) {
        if (req.getProductCode() == null) {
            return Result.failed(SystemError.HOTEL_10035);
        } else if (req.getBegDate() == null) {
            return Result.failed(SystemError.HOTEL_10036);
        } else if (req.getEndDate() == null) {
            return Result.failed(SystemError.HOTEL_10037);
        }
        String CONTENT_WITH_NO_SIGN = "{\"mer_no\":\"9000000242\",\"method\":\"chimelong.trip.product.price.get\",\"sign\":\"\",\"nonce_str\":\"80c5a87d22ed461bbe91ec691a4d9874\",\"timestamp\":\"2021-03-26 10:13:01\",\"ver_no\":\"1.0\",\"body\":\"{\\\"getData\\\":[{\\\"productCode\\\":\\\"" + req.getProductCode() + "\\\",\\\"begDate\\\":\\\"" + req.getBegDate() + "\\\",\\\"endDate\\\":\\\"" + req.getEndDate() + "\\\"}]}\"}";
        String signAppendStr = new APISignUtil().contentJointTest(CONTENT_WITH_NO_SIGN);
        String toData = new APIAesUtil().aesEncodeBase64(signAppendStr, "1d70b9997df4946824810ebb069dbe28");//SIGN_KEY:"1d70b9997df4946824810ebb069dbe28"（长隆提供）
        String params =
                "{" +
                        "\"mer_no\":\"9000000242\"," +
                        "\"data\":\"" + toData + "\"" +
                        "}";
        String contentType = "application/json;charset=utf-8";
        String path = "http://47.244.225.190:8080/hub/product/ota/call2/gsa/chimelong/api.do";
        String returnStr = new APIAesUtil().aesDecodeBase64(APIUtil.callAPIFunc(contentType, path, params, "POST"), "1d70b9997df4946824810ebb069dbe28");
        System.out.println(returnStr);
        cn.hutool.json.JSONObject j = new JSONObject(returnStr);
        JSONArray priceData = j.getJSONObject("body").getJSONArray("priceData");
        List<ChimeLongScenicProductPriceDTO> chimeLongScenicProductPriceDTOS = (List<ChimeLongScenicProductPriceDTO>) JSON.parseArray(String.valueOf(priceData), ChimeLongScenicProductPriceDTO.class);
        if (CollectionUtils.isNotEmpty(chimeLongScenicProductPriceDTOS)) {
            for (ChimeLongScenicProductPriceDTO chimeLongScenicProductPriceDTO : chimeLongScenicProductPriceDTOS) {
                QueryWrapper<ScenicProduct> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("product_code", chimeLongScenicProductPriceDTO.getProductCode());
                queryWrapper.eq("is_deleted", 0);
                List<ScenicProduct> scenicProductList = scenicProductMapper.selectList(queryWrapper);
                if (CollectionUtils.isNotEmpty(scenicProductList)) {
                    //插入成本策略
                    ScenicProduct scenicProduct = scenicProductList.get(0);
                    ScenicProductCostStrategy scenicProductCostStrategy = new ScenicProductCostStrategy();
                    Long id = SnowflakeIdWorker.nextId();
                    scenicProductCostStrategy.setCurrency(chimeLongScenicProductPriceDTO.getCurrency());
                    scenicProductCostStrategy.setId(id);
                    scenicProductCostStrategy.setGmtCreate(LocalDateTime.now());
                    scenicProductCostStrategy.setCreateId(user.getId());
                    scenicProductCostStrategy.setProductId(scenicProduct.getId());
                    scenicProductCostStrategyMapper.insert(scenicProductCostStrategy);
                    //成本策略价格规格属性
                    ScenicProductCostStrategySpecAttr scenicProductCostStrategySpecAttr = new ScenicProductCostStrategySpecAttr();
                    scenicProductCostStrategySpecAttr.setProductId(scenicProduct.getId());
                    scenicProductCostStrategySpecAttr.setStrategyId(id);
                    List<SeasonData> seasonDatas = chimeLongScenicProductPriceDTO.getSeasonData();
                    for (SeasonData seasonData : seasonDatas) {
                        scenicProductCostStrategySpecAttr.setAttributeName(seasonData.getSeasonName());
                        scenicProductCostStrategySpecAttr.setGmtCreate(LocalDateTime.now());
                        scenicProductCostStrategySpecAttr.setCreateId(user.getId());
                        scenicProductCostStrategySpecAttr.setId(SnowflakeIdWorker.nextId());
                        scenicProductCostStrategySpecAttrMapper.insert(scenicProductCostStrategySpecAttr);
                    }
                    //门票成本价格加幅有效期
                    ScenicProductCostStrategyVaildDate scenicProductCostStrategyVaildDate = new ScenicProductCostStrategyVaildDate();
                    scenicProductCostStrategyVaildDate.setProductId(scenicProduct.getId());
                    scenicProductCostStrategyVaildDate.setStrategyId(id);
                    scenicProductCostStrategyVaildDate.setTimeBegin(LocalDate.now());
                    scenicProductCostStrategyVaildDate.setTimeEnd(LocalDate.now().plusDays(1));
                    scenicProductCostStrategyVaildDateMapper.insert(scenicProductCostStrategyVaildDate);
                }
            }
        }
        return Result.success();
    }

    @Override
    public Result chimeLongOrderCreate(ChimeLongCreateOrderPreDTO chimeLongCreateOrderPreDTO, TokenUser user) {
        String CREATEORDER = "{\"mer_no\":\"9000000242\",\"method\":\"chimelong.trip.order.create\",\"sign\":\"\",\"nonce_str\":\"80c5a87d22ed461bbe91ec691a4d9874\",\"timestamp\":\"2021-03-12 10:13:01\",\"ver_no\":\"1.0\",\"body\":\"{" +
                "\\\"otaOrderId\\\": \\\"" + chimeLongCreateOrderPreDTO.getOtaOrderId() + "\\\"," +
                "\\\"name\\\": \\\"" + chimeLongCreateOrderPreDTO.getName() + "\\\"," +
                "\\\"mobile\\\": \\\"" + chimeLongCreateOrderPreDTO.getMobile() + "\\\"," +
                "\\\"orderMoney\\\": \\\"" + chimeLongCreateOrderPreDTO.getOrderMoney() + "\\\"," +
                "\\\"currency\\\": \\\"" + chimeLongCreateOrderPreDTO.getCurrency() + "\\\"," +
                "\\\"productData\\\": [{" +
                "\\\"productCode\\\": \\\"" + chimeLongCreateOrderPreDTO.getProductData().get(0).getProductCode() + "\\\"," +
                "\\\"begDate\\\": \\\"" + chimeLongCreateOrderPreDTO.getProductData().get(0).getBegDate() + "\\\"," +
                "\\\"endDate\\\": \\\"" + chimeLongCreateOrderPreDTO.getProductData().get(0).getEndDate() + "\\\"," +
                "\\\"settlePrice\\\": " + chimeLongCreateOrderPreDTO.getProductData().get(0).getSettlePrice() + "," +
                "\\\"otaPrice\\\": " + chimeLongCreateOrderPreDTO.getProductData().get(0).getOtaPrice() + "," +
                "\\\"quantity\\\": " + chimeLongCreateOrderPreDTO.getProductData().get(0).getQuantity() + "," +
                "\\\"totalMoney\\\": " + chimeLongCreateOrderPreDTO.getProductData().get(0).getTotalMoney() + "," +
                "}]" +
                "}\"}";
        String signAppendStr = new APISignUtil().contentJointTest(CREATEORDER);
        String toData = new APIAesUtil().aesEncodeBase64(signAppendStr, "1d70b9997df4946824810ebb069dbe28");//SIGN_KEY:"1d70b9997df4946824810ebb069dbe28"（长隆提供）
        String params =
                "{" +
                        "\"mer_no\":\"9000000242\"," +
                        "\"data\":\"" + toData + "\"" +
                        "}";
        String contentType = "application/json;charset=utf-8";
        String path = "http://47.244.225.190:8080/hub/product/ota/call2/gsa/chimelong/api.do";
        String returnStr = new APIAesUtil().aesDecodeBase64(APIUtil.callAPIFunc(contentType, path, params, "POST"), "1d70b9997df4946824810ebb069dbe28");
        System.out.println(returnStr);

        if (!returnStr.contains("body")) {
            return Result.failed(SystemError.HOTEL_10050);
        } else {
            JSONObject j = new JSONObject(returnStr);
            JSONObject stockData = j.getJSONObject("body");
            return Result.success(stockData.get("chimeOrderId").toString());
        }
    }

    public Result<StockData> getProductStockChimeLong(ChimeLongProductPriceAndStockReq req) {
        String CONTENT_WITH_NO_SIGN = "{\"mer_no\":\"9000000242\",\"method\":\"chimelong.trip.product.stock.get\",\"sign\":\"\",\"nonce_str\":\"80c5a87d22ed461bbe91ec691a4d9874\",\"timestamp\":\"2021-03-26 10:13:01\",\"ver_no\":\"1.0\",\"body\":\"{\\\"getData\\\":[{\\\"productCode\\\":\\\"" + req.getProductCode() + "\\\",\\\"begDate\\\":\\\"" + req.getBegDate() + "\\\",\\\"endDate\\\":\\\"" + req.getEndDate() + "\\\"}]}\"}";
        String signAppendStr = new APISignUtil().contentJointTest(CONTENT_WITH_NO_SIGN);
        String toData = new APIAesUtil().aesEncodeBase64(signAppendStr, "1d70b9997df4946824810ebb069dbe28");//SIGN_KEY:"1d70b9997df4946824810ebb069dbe28"（长隆提供）
        String params =
                "{" +
                        "\"mer_no\":\"9000000242\"," +
                        "\"data\":\"" + toData + "\"" +
                        "}";
        String contentType = "application/json;charset=utf-8";
        String path = "http://47.244.225.190:8080/hub/product/ota/call2/gsa/chimelong/api.do";
        String returnStr = new APIAesUtil().aesDecodeBase64(APIUtil.callAPIFunc(contentType, path, params, "POST"), "1d70b9997df4946824810ebb069dbe28");
        List<StockData> stockDataList = null;
        if (!returnStr.equals("") || returnStr != null) {
            JSONObject j = new JSONObject(returnStr);
            JSONArray stockData = j.getJSONObject("body").getJSONArray("stockData");
            stockDataList = (List<StockData>) JSON.parseArray(String.valueOf(stockData), StockData.class);
        }
        StockData stockData = null;
        if (CollectionUtils.isNotEmpty(stockDataList)) {
            stockData = stockDataList.get(0);
        }
        return Result.success(stockData);
    }


    /**
     * 长隆订单取消
     */
    @Override
    public Result chimeLongOrderCancel(String chimeLongIdOrOtaId, TokenUser user) {
        String cancelOrder = "{\"mer_no\":\"9000000242\",\"method\":\"chimelong.trip.order.cancel\",\"sign\":\"\",\"nonce_str\":\"80c5a87d22ed461bbe91ec691a4d9874\",\"timestamp\":\"2021-03-26 10:13:01\",\"ver_no\":\"1.0\",\"body\":\"{\\\"chimeOrderId\\\":\\\"" + chimeLongIdOrOtaId + "\\\"}\"}";

        String signAppendStr = new APISignUtil().contentJointTest(cancelOrder);
        String toData = new APIAesUtil().aesEncodeBase64(signAppendStr, "1d70b9997df4946824810ebb069dbe28");//SIGN_KEY:"1d70b9997df4946824810ebb069dbe28"（长隆提供）
        String params =
                "{" +
                        "\"mer_no\":\"9000000242\"," +
                        "\"data\":\"" + toData + "\"" +
                        "}";
        String contentType = "application/json;charset=utf-8";
        String path = "http://47.244.225.190:8080/hub/product/ota/call2/gsa/chimelong/api.do";
        String returnStr = new APIAesUtil().aesDecodeBase64(APIUtil.callAPIFunc(contentType, path, params, "POST"), "1d70b9997df4946824810ebb069dbe28");
        System.out.println(returnStr);

        if (!returnStr.contains("body")) {
            return Result.failed(SystemError.HOTEL_10051);
        } else {
            return Result.success(returnStr);
        }
    }

    @Override
    public Result<List<ScenicProductListDTO>> getListByIds(ScenicProductListReq scenicProductListReq) {
        List<ScenicProductListDTO> scenicProductListDTOList = null;
        if (CollectionUtils.isNotEmpty(scenicProductListReq.getIds())) {
            QueryWrapper<ScenicProduct> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", scenicProductListReq.getIds());
            queryWrapper.eq("is_deleted", 0);
            List<ScenicProduct> scenicProductList = scenicProductMapper.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(scenicProductList)) {
                scenicProductListDTOList = EntityUtil.copyList(scenicProductList, ScenicProductListDTO.class);
            }
        }
        return Result.success(scenicProductListDTOList);
    }

    @Override
    public Result<ScenicProductListDTO> queryById(Long id) {
        ScenicProduct scenicProduct = scenicProductMapper.selectById(id);
        ScenicProductListDTO dto = new ScenicProductListDTO();
        if (scenicProduct != null) {
            dto = EntityUtil.copy(scenicProduct, ScenicProductListDTO.class);
        }
        return Result.success(dto);
    }

    @Override
    public Result<List<ScenicProductListDTO>> queryList(String ids) {
        List<ScenicProductListDTO> scenicProductListDTOS = scenicProductMapper.selectProductList(ids);
        return Result.success(scenicProductListDTOS);
    }

    @Override
    public Result<List<ScenicProductEsDTO>> queryListByEs() {
        return Result.success(scenicProductMapper.selectAllProductList());
    }

    @Override
    public Result<List<ScenicProductEsDTO>> queryListByEsAll() {
        scenicProductMapper.selectList(Wrappers.lambdaQuery());
        return null;
    }

    @Override
    public Result<List<ScenicProductEsDTO>> queryListByEsAndGmtModified(String gmtModified) {
        return Result.success(scenicProductMapper.selectAllProductListByGmtModified(gmtModified));
    }

    @Override
    public List<ScenicProductChannelOnlineSelfPlatformDTO> queryListByProductId(Long productId) {
        List<ScenicProductChannelOnlineSelfPlatformDTO> scenicProductChannelOnlineSelfPlatformDTOS = scenicProductChannelOnlineSelfPlatformMapper.selectChannelTypeListByProductId(productId);
        if (scenicProductChannelOnlineSelfPlatformDTOS == null) {
            return new ArrayList<>();
        }
        return scenicProductChannelOnlineSelfPlatformDTOS;
    }

    @Override
    public List<ScenicProductEsDTO> queryProductPriceByScenicProductEsList(List<ScenicProductEsDTO> scenicProductEsDTOS) {
        if (scenicProductEsDTOS == null) {
            return new ArrayList<>();
        }
        scenicProductEsDTOS.stream().forEach(item -> {
            // 价格规则
            // 1. 根据产品ID 查找产品所有的价格属性
        });
        return scenicProductEsDTOS;
    }

    /**
     * 产品成本日期校验
     *
     * @param strategyList
     * @return
     */
    private Result<Object> checkCostateResult(List<ScenicProductSaleStrategyReq> strategyList) {
        List<ScenicTimeDTO> scenicTimeDTOList = new ArrayList<>();
        // 四种渠道至少有一个在售校验
        for (ScenicProductSaleStrategyReq req : strategyList) {
            scenicTimeDTOList.addAll(req.getTime());
        }
        for (int i = 0; i < scenicTimeDTOList.size(); i++) {
            ScenicTimeDTO scenicTimeDTO = scenicTimeDTOList.get(i);
            if (scenicTimeDTO.getBeginTime().isBefore(LocalDate.now())) {
                // 门票产品加幅策略保存，开始日期不能小于当前日期校验
                return Result.failed(SystemError.BUS_PRODUCT_9024);
            }
            if (i == 0 && scenicTimeDTO.getBeginTime().isAfter(scenicTimeDTO.getEndTime())) {
                // 开始日期必须小于结束日期校验
                return Result.failed(SystemError.BUS_PRODUCT_9021);
            }
//            for (int j = 0; j < scenicTimeDTOList.size(); j++) {
//                ScenicTimeDTO scenicTime = scenicTimeDTOList.get(j);
//                if (i >= j) { // 自身和已经校验过的跳过日期校验
//                    continue;
//                }
//                if (i == 0 && scenicTime.getBeginTime().isAfter(scenicTime.getEndTime())) {
//                    // 开始日期必须小于结束日期校验
//                    return Result.failed(SystemError.BUS_PRODUCT_9021);
//                }
//            }
        }
        return null;
    }

    @Override
    public Result<List<ScenicProductChannelOfflineAgentCustomDTO>>
    getAgentListByProductId(Long productId, String stockId, TokenUser tokenUser, String name) {
        QueryWrapper<ScenicProduct> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.eq("id", productId);
        ScenicProduct scenicProduct = scenicProductMapper.selectOne(productQueryWrapper);
        List<ScenicProductChannelOfflineAgentCustomDTO> agentCustomDTOS = new ArrayList<>();
        ScenicProductSaleStrategyVaildDate saleStrategyVaildDate =
                scenicProductSaleStrategyVaildDateMapper.queryDetail(DateUtil.fmt(LocalDateTime.now()), productId);
        if (saleStrategyVaildDate != null) {
            QueryWrapper<ScenicProductChannelOffline> queryWrapperOfline = new QueryWrapper<>();
            queryWrapperOfline.eq("product_id", productId);
            queryWrapperOfline.eq("is_deleted", IsDeletedCode.NO.getCode());
            queryWrapperOfline.eq("strategy_id", saleStrategyVaildDate.getStrategyId());
            // 线下渠道类型（1：自营渠道 2：代理商）
            queryWrapperOfline.eq("channel_type", 2);
            //查询上线的权限
            ScenicProductChannelOffline scenicProductChannelOffline = scenicProductChannelOfflineMapper.selectOne(queryWrapperOfline);
            if (!Objects.isNull(scenicProductChannelOffline)) {
                QueryWrapper<ScenicProductChannelOffline> offlineQueryWrapper = new QueryWrapper<>();
                offlineQueryWrapper.eq("id", scenicProductChannelOffline.getId());
                ScenicProductChannelOffline offline = scenicProductChannelOfflineMapper.selectOne(offlineQueryWrapper);
                BigDecimal constPrice = iScenicReservationService.queryCostByProductId(productId, Long.parseLong(stockId)).getPrice();
                QueryWrapper<ScenicProductChannelOfflineAgentCustom> agentCustomQueryWrapper = new QueryWrapper<>();
                agentCustomQueryWrapper.eq("offline_id", scenicProductChannelOffline.getId());
                agentCustomQueryWrapper.eq("is_deleted", IsDeletedCode.NO.getCode());
                //查询
                List<ScenicProductChannelOfflineAgentCustom> list =
                        scenicProductChannelOfflineAgentCustomMapper.selectList(agentCustomQueryWrapper);
                switch (offline.getVisableType()) {
                    /**
                     先查询出 增幅  然后模糊查询出代理商
                     */
                    case 2:
                        //查询所有的 代理商的增幅计算
                        List<QueryAgentByNameDTO> result = iSysAgentService.queryAgentByName(name).getData();
                        if (!CollectionUtils.isEmpty(result)) {
                            for (QueryAgentByNameDTO dto : result) {
                                ScenicProductChannelOfflineAgentCustom custom = list.get(0);
                                agentCustomDTOS.add(calculateByOfflineAgentCustomDTO(
                                        constPrice,
                                        custom,
                                        offline.getVisableType().toString(),
                                        scenicProduct,
                                        dto));
                            }
                        }
                        break;
                    case 3:
                        //查询所有指定的代理商  在指定的代理商中进行模糊搜索  然后进行计算
                        //查询
                        if (!CollectionUtils.isEmpty(list)) {
                            Map<Long, ScenicProductChannelOfflineAgentCustom> map = new HashMap<>();
                            for (ScenicProductChannelOfflineAgentCustom custom : list) {
                                map.put(custom.getAgentId(), custom);
                            }
                            List<Long> relaids = list.stream().map(ScenicProductChannelOfflineAgentCustom::getAgentId).collect(Collectors.toList());
                            List<QueryAgentByNameDTO> agentByNameDTOS = iSysAgentService.queryAgentByNameAndIds(name, relaids).getData();
                            if (!CollectionUtils.isEmpty(agentByNameDTOS)) {
                                for (QueryAgentByNameDTO dto : agentByNameDTOS) {
                                    agentCustomDTOS.add(calculateByOfflineAgentCustomDTO(
                                            constPrice,
                                            map.get(dto.getId()),
                                            offline.getVisableType().toString(),
                                            scenicProduct,
                                            dto));
                                }
                            }

                        }
                        break;
                }
            }
        }
        return Result.success(agentCustomDTOS);
    }

    @Override
    public Result synTaskScenicByEs() {
        return Result.success(putData());
    }


    /**
     * 单纯地计算增幅
     *
     * @param constPrice
     * @param custom
     * @param visableTyp
     * @param scenicProduct
     * @param dto
     * @return
     */
    private ScenicProductChannelOfflineAgentCustomDTO calculateByOfflineAgentCustomDTO(BigDecimal constPrice,
                                                                                       ScenicProductChannelOfflineAgentCustom custom,
                                                                                       String visableTyp,
                                                                                       ScenicProduct scenicProduct,
                                                                                       QueryAgentByNameDTO dto) {

        ScenicProductChannelOfflineAgentCustomDTO customDTO = new ScenicProductChannelOfflineAgentCustomDTO();
        customDTO.setVisableType(visableTyp);
        customDTO.setAgentName(dto.getCnName());
        customDTO.setAgentId(dto.getId());
        customDTO.setAdjustType(custom.getAdjustType());
        customDTO.setAmount(custom.getAmount());
        customDTO.setPercent(custom.getPercent());
        customDTO.setIsLimit(custom.getIsLimit());
        customDTO.setLimitNum(custom.getLimitNum());
        switch (scenicProduct.getReserveChargeType()) {
            case 1:
                customDTO.setReserveCharge(scenicProduct.getReserveCharge());
                break;
            case 2:
                customDTO.setReserveCharge(constPrice.multiply(scenicProduct.getReserveCharge()).divide(new BigDecimal("100")));
                break;
        }
        customDTO.setPrice(constPrice.add(customDTO.getReserveCharge()));
        switch (custom.getAdjustType()) {
            case 1:
                customDTO.setAllPrice(constPrice.add(custom.getAmount()));
                break;
            case 2:
                customDTO.setAllPrice(constPrice.add(constPrice.multiply(BigDecimal.valueOf(custom.getPercent())).divide(new BigDecimal("100"))));
                break;
        }
        customDTO.setAllPrice(customDTO.getAllPrice().setScale(2, BigDecimal.ROUND_UP));
        customDTO.setReserveCharge(customDTO.getReserveCharge().setScale(2, BigDecimal.ROUND_UP));
        return customDTO;
    }


    private boolean createIndex() {
        try {
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(ElasticSearchConstant.SCENIC);

            Map<String, Object> mapping = new HashMap<>();
            Map<String, Object> properties = new HashMap<>();

            // 文本类型
            Map<String, Object> typeMap = new HashMap<>();
            typeMap.put("type", "keyword");
            // 时间类型
            Map<String, Object> timeMap = new HashMap<>();
            timeMap.put("type", "date");

            List<String> fields = new ArrayList<>();
            fields.add("id");

            // 渠道ID
            fields.add("channelId");
            // 渠道名称
            fields.add("channelName");
            // 策略ID
            fields.add("strategyId");
            // 策略名称
            fields.add("strategyName");
            // 产品ID
            fields.add("productId");
            // 产品名称
            fields.add("productName");
            // 是否推荐
            fields.add("isRecommend");
            // 城市ID
            fields.add("cityId");
            // 城市名称
            fields.add("cityName");
            // 产品描述
            fields.add("productIntroduces");
            // 主题JSON
            fields.add("themeJson");
            // 图片JSON
            fields.add("photosJson");
            // 预订服务费类型
            fields.add("reserveChargeType");
            // 预订服务费
            fields.add("reserveCharge");
            // 加幅类型
            fields.add("adjustType");
            // 加幅金额
            fields.add("amount");
            // 加幅百分比
            fields.add("precent");
            // 销售开始时间
            fields.add("saleTimeBegin");
            // 销售结束时间
            fields.add("saleTimeEnd");
            // 产品修改时间
            fields.add("gmtModified");
            // 上架状态
            fields.add("status");
            // 售卖状态
            fields.add("saleStatus");
            // 产品删除状态
            fields.add("isDeleted");
            // 产品成本价
            fields.add("costPrice");
            // 汇率
            fields.add("exchangeRate");
            // 门票类型
            fields.add("attr2Name");
            // 门票规格
            fields.add("attr1Name");
            // 已销售数量
            fields.add("soldStock");
            // 负责人ID
            fields.add("chargeUserId");
            // 负责人名称
            fields.add("chargeUser");
            // 供应商ID
            fields.add("supplierId");
            // 供应商名称
            fields.add("supplierName");
            // 是否需要填写联系人信息
            fields.add("needInfo");
            // 入园须知
            fields.add("admissionNotes");
            // 预订后是否可退
            fields.add("allowRefund");
            // 产品分类名称
            fields.add("productTypeName");
            // 规格ID
            fields.add("attrId");
            // 几日有效
            fields.add("validDay");

            for (String field : fields) {
                properties.put(field, JSON.parse(JSON.toJSONString(typeMap)));
            }

            mapping.put("properties", properties);
            createIndexRequest.mapping(JSON.toJSONString(mapping), XContentType.JSON);
            restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private boolean deleteIndex() {
        try {
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(ElasticSearchConstant.SCENIC);
            restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private boolean putData() {
        try {
            log.info("=========================== time :" + lastModifiedTime);
            // 判断索引是否存在
            GetIndexRequest getIndexRequest = new GetIndexRequest(ElasticSearchConstant.SCENIC);
            boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
            if (!exists) {
                // 不存在则创建
                createIndex();
                lastModifiedTime = null;
            }

            if (lastModifiedTime == null) {
                // 全量更新操作 1.删除索引并重新添加数据
                if (deleteIndex()) {
                    createIndex();
                    // 查询所有的数据然后新增到参数中
                    Result<List<ScenicProductEsDTO>> listResult = queryListByEs();
                    log.info("查询语句响应结果：" + listResult.getData().size());
                    if (listResult.isSuccess()) {
                        List<ScenicProductEsDTO> data = listResult.getData();
                        for (ScenicProductEsDTO item : data) {
                            IndexRequest indexRequest = new IndexRequest(ElasticSearchConstant.SCENIC);
                            indexRequest.id(String.valueOf(item.getProductId()));
                            indexRequest.source(JSON.toJSONString(item), XContentType.JSON);
                            try {
                                restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        // 将最后一个产品的更新时间作为检查时间，而不是当前调度时间
                        if (data.size() > 0) {
                            lastModifiedTime = data.get(0).getGmtModified();
                        }
                    }
                }
            } else {
                // 增量更新操作 1. 查询时间之后的数据
                String formatTime = lastModifiedTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                Result<List<ScenicProductEsDTO>> listResult = queryListByEsAndGmtModified(formatTime);
                log.info("ADD查询语句响应结果：" + listResult.getData().size());
                if (listResult.isSuccess()) {
                    List<ScenicProductEsDTO> data = listResult.getData();
                    for (ScenicProductEsDTO item : data) {
                        // 查询数据是否存在
                        GetRequest getRequest = new GetRequest(ElasticSearchConstant.SCENIC);
                        getRequest.id(String.valueOf(item.getProductId()));
                        boolean haveFlag = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
                        if (!haveFlag) {
                            // 创建
                            IndexRequest indexRequest = new IndexRequest(ElasticSearchConstant.SCENIC);
                            indexRequest.id(String.valueOf(item.getProductId()));
                            indexRequest.source(JSON.toJSONString(item), XContentType.JSON);
                            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
                        } else {
                            // 更新
                            UpdateRequest updateRequest = new UpdateRequest();
                            updateRequest.index(ElasticSearchConstant.SCENIC);
                            updateRequest.id(String.valueOf(item.getProductId()));
                            updateRequest.doc(JSON.toJSONString(item), XContentType.JSON);
                            restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
                        }
                    }
                    // 将最后一个产品的更新时间作为检查时间，而不是当前调度时间
                    if (data.size() > 0) {
                        lastModifiedTime = data.get(0).getGmtModified();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

}
